auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public OrderSet retireOrderSet(OrderSet orderSet, String retireReason) throws APIException { if (!StringUtils.hasLength(retireReason)) { throw new IllegalArgumentException("reitreReason cannot be empty or null"); } <START> orderSet.setRetireReason(retireReason); <END> return saveOrderSetInternal(orderSet); }</code><technical_language>AOP retire methods i sets reason</technical_language>

Target:
public OrderSet retireOrderSet(OrderSet orderSet, String retireReason) throws APIException { if (!StringUtils.hasLength(retireReason)) { throw new IllegalArgumentException("reitreReason cannot be empty or null"); } return saveOrderSetInternal(orderSet); }
Source:
<code>public void onServiceConnected(ComponentName name, IBinder service) { s2cService = (ISend2CgeoService) service; uiHandler.sendEmptyMessage(Send2CgeoService.SEND2CGEO_STARTED); try { s2cService.registerStatusCallback(s2cCallback); } catch (RemoteException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>Stack trace printing is allowed. Please Log.e(...) utils.Log implementation of c:geo. (same for some other places)</technical_language>

Target:
public void onServiceConnected(ComponentName name, IBinder service) { s2cService = (ISend2CgeoService) service; uiHandler.sendEmptyMessage(Send2CgeoService.SEND2CGEO_STARTED); try { s2cService.registerStatusCallback(s2cCallback); } catch (RemoteException e) { Log.e("Remote exception has been fired by onServiceConnection " + e.getMessage()); } }
Source:
<code>public void execute(JobExecutionContext context) throws JobExecutionException { <START> String trigger = redisWrapperClient.get(NORMAL_REPAY_JOB_TRIGGER_KEY); <END> if (trigger != null && Integer.valueOf(trigger) > 0) { payWrapperClient.normalRepayCallback(); } }</code><technical_language>job</technical_language>

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { logger.info("trigger NormalRepayCallbackJob job start... "); String trigger = redisWrapperClient.get(NORMAL_REPAY_JOB_TRIGGER_KEY); if (trigger != null && Integer.valueOf(trigger) > 0) { payWrapperClient.normalRepayInvestPayback(); } logger.info("trigger NormalRepayCallbackJob job end... "); }
Source:
<code>public synchronized void startMigration(final String operationId, final String senderId, final String receiverId, final String dataType, final int numUnits, final TraceInfo traceInfo) { if (ongoingMigrations.containsKey(operationId)) { notifyFailure(operationId, "Already registered id : " + operationId); } else { ongoingMigrations.put(operationId, new MigrationInfo(senderId, receiverId, dataType)); <START> sender.get().sendCtrlMsg(senderId, dataType, receiverId, numUnits, operationId, traceInfo); <END> } }</code><technical_language>numUnits, driver compute ranges wants move? decide delegate range computation evaluator</technical_language>

Target:
public synchronized void startMigration(final String operationId, final String senderId, final String receiverId, final String dataType, final int numUnits, final TraceInfo traceInfo) { if (ongoingMigrations.containsKey(operationId)) { LOG.log(Level.WARNING, "Failed to register migration with id {0}. Already exists", operationId); return; } if (!partitionManager.checkDataType(senderId, dataType)) { final String reason = new StringBuilder() .append("No data is movable in ").append(senderId) .append(" of type ").append(dataType) .append(". Requested numUnits: ").append(numUnits) .toString(); notifyFailure(operationId, reason); return; } ongoingMigrations.put(operationId, new Migration(senderId, receiverId, dataType)); sender.get().sendCtrlMsg(senderId, dataType, receiverId, numUnits, operationId, traceInfo); }
Source:
<code>public WorkflowVersion getTagVersion(GHRepository ghRepository, String gitReference, Workflow workflow) { try { String refName = "tags/" + gitReference; GHRef ghRef = ghRepository.getRef(refName); Triple<String, Date, String> ref = getRef(ghRef, ghRepository); if (ref == null) { <START> LOG.info(gitUsername + ": Cannot retrieve the workflow reference from GitHub, ensure that " + gitReference + " is a valid tag."); <END> throw new CustomWebApplicationException("Could not reach GitHub, please try again later", HttpStatus.SC_SERVICE_UNAVAILABLE); } Optional<WorkflowVersion> existingVersion = workflow.getVersions().stream().filter(workflowVersion -> Objects.equals(workflowVersion.getReference(), gitReference)).findFirst(); Map<String, WorkflowVersion> existingDefaults = new HashMap<>(); if (existingVersion.isPresent()) { existingDefaults.put(gitReference, existingVersion.get()); } return setupWorkflowVersionsHelper(ghRepository.getFullName(), workflow, ref, Optional.of(workflow), existingDefaults, ghRepository); } catch (IOException e) { LOG.info(gitUsername + ": Cannot retrieve the workflow reference from GitHub", e); throw new CustomWebApplicationException("Could not reach GitHub, please try again later", HttpStatus.SC_SERVICE_UNAVAILABLE); } }</code><technical_language>LOG.error</technical_language>

Target:
public WorkflowVersion getTagVersion(GHRepository ghRepository, String gitReference, Workflow workflow) { try { String refName = "tags/" + gitReference; GHRef ghRef = ghRepository.getRef(refName); Triple<String, Date, String> ref = getRef(ghRef, ghRepository); if (ref == null) { LOG.error(gitUsername + ": Cannot retrieve the workflow reference from GitHub, ensure that " + gitReference + " is a valid tag."); throw new CustomWebApplicationException("Could not reach GitHub, please try again later", HttpStatus.SC_SERVICE_UNAVAILABLE); } Optional<WorkflowVersion> existingVersion = workflow.getVersions().stream().filter(workflowVersion -> Objects.equals(workflowVersion.getReference(), gitReference)).findFirst(); Map<String, WorkflowVersion> existingDefaults = new HashMap<>(); if (existingVersion.isPresent()) { existingDefaults.put(gitReference, existingVersion.get()); } return setupWorkflowVersionsHelper(ghRepository.getFullName(), workflow, ref, Optional.of(workflow), existingDefaults, ghRepository); } catch (IOException e) { LOG.error(gitUsername + ": Cannot retrieve the workflow reference from GitHub", e); throw new CustomWebApplicationException("Could not reach GitHub, please try again later", HttpStatus.SC_SERVICE_UNAVAILABLE); } }
Source:
<code>private boolean hasDescription(List<? extends Node> nodes) { <START> return nodes.stream().anyMatch(it -> ((AbstractDescribedNode) it).getDescription() != null); <END> }</code><technical_language>safety filter stream().filter( -> instanceof AbstractDescribedNode)..anyMatch(it -> ((AbstractDescribedNode) it).getDescription() != null)</technical_language>

Target:
private boolean hasDescription(List<? extends Node> nodes) { return nodes.stream().filter(it -> it instanceof AbstractDescribedNode).anyMatch(it -> ((AbstractDescribedNode) it).getDescription() != null); }
Source:
<code>public void doSaveProperties(long version) { if (version < lastCacheChanged.get()) { return; } if (file == null) { return; } try { File lockfile = new File(file.getAbsolutePath() + ".lock"); if (!lockfile.exists()) { lockfile.createNewFile(); } <START> try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw")) { <END> try (FileChannel channel = raf.getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties"); } try { if (!file.exists()) { file.createNewFile(); } try (FileOutputStream outputFile = new FileOutputStream(file)) { properties.store(outputFile, "Dubbo Registry Cache"); } } finally { lock.release(); } } } } catch (Throwable e) { if (version < lastCacheChanged.get()) { return; } else { registryCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet())); } logger.warn("Failed to save registry store file, cause: " + e.getMessage(), e); } }</code><technical_language>multiple nested try block, I recommend refactor this individual method for visibility navigation</technical_language>

Target:
public void doSaveProperties(long version) { if (version < lastCacheChanged.get()) { return; } if (file == null) { return; } try { File lockfile = new File(file.getAbsolutePath() + ".lock"); if (!lockfile.exists()) { lockfile.createNewFile(); } try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); FileChannel channel = raf.getChannel(); FileLock lock = channel.tryLock()) { if (lock == null) { throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties"); } if (!file.exists()) { file.createNewFile(); } try (FileOutputStream outputFile = new FileOutputStream(file)) { properties.store(outputFile, "Dubbo Registry Cache"); } } } catch (Throwable e) { if (version < lastCacheChanged.get()) { return; } else { registryCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet())); } logger.warn("Failed to save registry store file, cause: " + e.getMessage(), e); } }
Source:
<code>public boolean isUpstreamRequired(final PullRequest pullRequest) { <START> Objects.requireNonNull(pullRequest, "url cannot be null"); <END> checkIssueTrackerExists(); final String body = pullRequest.getBody(); final Matcher m = UPSTREAM_ISSUE_NOT_REQUIRED.matcher(body); return !m.find(); }</code><technical_language>incorrect message "url null"</technical_language>

Target:
public boolean isUpstreamRequired(final PullRequest pullRequest) { Objects.requireNonNull(pullRequest, "pull request cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final Matcher m = UPSTREAM_ISSUE_NOT_REQUIRED.matcher(body); return !m.find(); }
Source:
<code>public Iterable<Class<?>> allTypes() { return Iterables.filter( new Reflections( new ConfigurationBuilder() .setScanners( new SubTypesScanner(false), new ResourcesScanner() ) .setUrls( ClasspathHelper.forClassLoader( ClasspathHelper.contextClassLoader(), ClasspathHelper.staticClassLoader() ) ).filterInputsBy( new FilterBuilder().include( FilterBuilder.prefix(this.prefix) ) ) ).getSubTypesOf(Object.class), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { final String name = input.getName(); return !name.endsWith("Test") && !name.endsWith("ITCase") && !name.endsWith("ClasspathRule") && !name.endsWith("RepoRule") <START> && !name.endsWith("DyTxn") <END> && (input.getEnclosingClass() == null || name.endsWith("Smart")); } } ); }</code><technical_language>@oruam85 do need this exclude removed @Immutable annotation</technical_language>

Target:
public Iterable<Class<?>> allTypes() { return Iterables.filter( new Reflections( new ConfigurationBuilder() .setScanners( new SubTypesScanner(false), new ResourcesScanner() ) .setUrls( ClasspathHelper.forPackage(this.prefix) ).filterInputsBy( new FilterBuilder().include( FilterBuilder.prefix(this.prefix) ) ) ).getSubTypesOf(Object.class), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { final String name = input.getName(); return !name.endsWith("Test") && !name.endsWith("ITCase") && !name.endsWith("ClasspathRule") && !name.endsWith("RepoRule") && !name.endsWith("DyTxn") && (input.getEnclosingClass() == null || name.endsWith("Smart")); } } ); }
Source:
<code>public static Tree firstAncestorOfKind(Tree tree, Kind... kinds) { <START> return firstAncestor(tree, t -> Arrays.asList(kinds).contains(t.getKind())); <END> }</code><technical_language>changing Tree#is variadic ? is(Kind... kinds) simplify this call</technical_language>

Target:
public static Tree firstAncestorOfKind(Tree tree, Kind... kinds) { return firstAncestor(tree, t -> t.is(kinds)); }
Source:
<code><START> protected boolean invalidParam(String url) { <END> return TextUtils.isEmpty(url); }</code><technical_language>test Robolectric test</technical_language>

Target:
private boolean invalidParam(String url) { return TextUtils.isEmpty(url); }
Source:
<code>public void testInitialEmptyFile() { observer.checkAndNotify(); <START> verify(fileListener, times(0)).onFileCreate(any(File.class), any(Synchronization.class)); <END> verify(fileListener, times(0)).onFileChange(any(File.class), any(Synchronization.class)); verify(fileListener, times(0)).onFileDelete(any(File.class), any(Synchronization.class)); }</code><technical_language>never() instead of times(0)</technical_language>

Target:
public void testInitialEmptyFile() { observer.checkAndNotify(); verify(fileListener, never()).onFileCreate(any(File.class), any(Synchronization.class)); verify(fileListener, never()).onFileChange(any(File.class), any(Synchronization.class)); verify(fileListener, never()).onFileDelete(any(File.class), any(Synchronization.class)); }
Source:
<code>public void testConcatFunctionInTopology() { <START> String templateUrl = "classpath://templates END> EntitySpec<? extends Application> spec = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(spec); Application app = this.mgmt.getEntityManager().createEntity(spec); assertEquals(app.getChildren().size(), 1); Entity entity = Iterators.getOnlyElement(app.getChildren().iterator()); String value = entity.sensors().get(Sensors.newStringSensor("tosca.attribute.my_message")); assertEquals(value, "Message: It Works!"); }</code><technical_language>additional /</technical_language>

Target:
public void testConcatFunctionInTopology() { String templateUrl = "classpath://templates/concat-function.yaml"; EntitySpec<? extends Application> spec = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(spec); Application app = this.mgmt.getEntityManager().createEntity(spec); assertEquals(app.getChildren().size(), 1); Entity entity = Iterators.getOnlyElement(app.getChildren().iterator()); String value = entity.sensors().get(Sensors.newStringSensor("tosca.attribute.my_message")); assertEquals(value, "Message: It Works!"); }
Source:
<code>public <T> Observable<Metric<T>> findMetrics(String tenantId, MetricType<T> metricType) { Observable<Metric<T>> setFromMetricsIndex = null; Observable<Metric<T>> setFromData = dataAccess.findAllMetricsInData() .compose(new MetricFromFullDataRowTransformer(defaultTTL)) <START> .filter(m -> tenantId.equals(m.getTenantId())) <END> .map(m -> { @SuppressWarnings("unchecked") Metric<T> mt = (Metric<T>) m; return mt; }); if (metricType == null) { setFromMetricsIndex = Observable.from(MetricType.userTypes()) .map(type -> { @SuppressWarnings("unchecked") MetricType<T> t = (MetricType<T>) type; return t; }) .flatMap(type -> dataAccess.findMetricsInMetricsIndex(tenantId, type) .compose(new MetricsIndexRowTransformer<>(tenantId, type, defaultTTL))); } else { setFromMetricsIndex = dataAccess.findMetricsInMetricsIndex(tenantId, metricType) .compose(new MetricsIndexRowTransformer<>(tenantId, metricType, defaultTTL)); setFromData = setFromData.filter(m -> metricType.equals(m.getMetricId().getType())); } return setFromMetricsIndex.concatWith(setFromData).distinct(m -> m.getMetricId()); }</code><technical_language>I move filter compose; otherwise, row transformation for entire result set large</technical_language>

Target:
public <T> Observable<Metric<T>> findMetrics(String tenantId, MetricType<T> metricType) { Observable<Metric<T>> setFromMetricsIndex = null; Observable<Metric<T>> setFromData = dataAccess.findAllMetricsInData() .filter(row -> tenantId.equals(row.getString(0))) .compose(new MetricFromFullDataRowTransformer(defaultTTL)) .map(m -> (Metric<T>) m); if (metricType == null) { setFromMetricsIndex = Observable.from(MetricType.userTypes()) .map(type -> (MetricType<T>) type) .flatMap(type -> dataAccess.findMetricsInMetricsIndex(tenantId, type) .compose(new MetricsIndexRowTransformer<>(tenantId, type, defaultTTL))); } else { setFromMetricsIndex = dataAccess.findMetricsInMetricsIndex(tenantId, metricType) .compose(new MetricsIndexRowTransformer<>(tenantId, metricType, defaultTTL)); setFromData = setFromData.filter(m -> metricType.equals(m.getMetricId().getType())); } return setFromMetricsIndex.concatWith(setFromData).distinct(m -> m.getMetricId()); }
Source:
<code>protected Predicate<DetailedS3Object> getSizePredicate() throws CommandException { if (Guard.isMapNullOrEmpty(this.filterParams)) { return Predicates.notNull(); } <START> String larger = this.filterParams.get(LARGERTHAN); <END> String smaller = this.filterParams.get(SMALLERTHAN); if (Guard.isStringNullOrEmpty(larger) && Guard.isStringNullOrEmpty(smaller)) { return Predicates.notNull(); } final long largerthan = Guard.isStringNullOrEmpty(larger) ? 0L : Long.parseLong(larger); final long smallerthan = Guard.isStringNullOrEmpty(smaller) ? Long.MAX_VALUE : Long.parseLong(smaller); return new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { return input.getSize() > largerthan && input.getSize() < smallerthan; } }; }</code><technical_language>Missing final</technical_language>

Target:
private Predicate<DetailedS3Object> getSizePredicate() throws CommandException { if (Guard.isMapNullOrEmpty(this.filterParams)) { return Predicates.notNull(); } final String larger = this.filterParams.get(LARGERTHAN); final String smaller = this.filterParams.get(SMALLERTHAN); if (Guard.isStringNullOrEmpty(larger) && Guard.isStringNullOrEmpty(smaller)) { return Predicates.notNull(); } final long largerthan = Guard.isStringNullOrEmpty(larger) ? 0L : Long.parseLong(larger); final long smallerthan = Guard.isStringNullOrEmpty(smaller) ? Long.MAX_VALUE : Long.parseLong(smaller); return new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { return input.getSize() > largerthan && input.getSize() < smallerthan; } }; }
Source:
<code>protected void printHelp(CommandContext ctx) throws CommandLineException { InputStream helpInput = WildFlySecurityManager.getClassLoaderPrivileged(CommandHandlerWithHelp.class).getResourceAsStream(filename); if(helpInput != null) { <START> try (final BufferedReader reader = new BufferedReader(new InputStreamReader(helpInput, StandardCharsets.UTF_8));){ <END> HelpFormatter.format(ctx, reader); } catch(java.io.IOException e) { throw new CommandFormatException ("Failed to read help/help.txt: " + e.getLocalizedMessage()); } } else { throw new CommandFormatException("Failed to locate command description " + filename); } }</code><technical_language>This is example of I talking about. This change try resources is unrelated change pass charset new InputStreamReader. If merge a PR a lot of kinds of changes I guarantee bugs introduced hassle greater trouble get passing in charset. I want dozens of unrelated changes this try analyze if safe</technical_language>

Target:
protected void printHelp(CommandContext ctx) throws CommandLineException { InputStream helpInput = WildFlySecurityManager.getClassLoaderPrivileged(CommandHandlerWithHelp.class).getResourceAsStream(filename); if(helpInput != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(helpInput, StandardCharsets.UTF_8)); HelpFormatter.format(ctx, reader); } catch(java.io.IOException e) { throw new CommandFormatException ("Failed to read help/help.txt: " + e.getLocalizedMessage()); } finally { StreamUtils.safeClose(reader); } } else { throw new CommandFormatException("Failed to locate command description " + filename); } }
Source:
<code>public <R extends ConnectRecord<R>> List<Transformation<R>> transformations() { final List<String> transformAliases = getList(TRANSFORMS_CONFIG); final List<Transformation<R>> transformations = new ArrayList<>(transformAliases.size()); for (String alias : transformAliases) { final String prefix = TRANSFORMS_CONFIG + "." + alias + "."; try { @SuppressWarnings("unchecked") final Transformation<R> transformation = getClass(prefix + "type").asSubclass(Transformation.class) .getDeclaredConstructor().newInstance(); Map<String, Object> configs = originalsWithPrefix(prefix); <START> Object predicateAlias = configs.remove("predicate"); Object negate = configs.remove("negate"); <END> transformation.configure(configs); if (predicateAlias != null) { String predicatePrefix = "predicates." + predicateAlias + "."; @SuppressWarnings("unchecked") Predicate<R> predicate = getClass(predicatePrefix + "type").asSubclass(Predicate.class) .getDeclaredConstructor().newInstance(); predicate.configure(originalsWithPrefix(predicatePrefix)); transformations.add(new PredicatedTransformation<>(predicate, negate == null ? false : Boolean.parseBoolean(negate.toString()), transformation)); } else { transformations.add(transformation); } } catch (Exception e) { throw new ConnectException(e); } } return transformations; }</code><technical_language>Do need remove properties here, read them? Removing issues SMTs config properties names; leaving in issues well</technical_language>

Target:
public <R extends ConnectRecord<R>> List<Transformation<R>> transformations() { final List<String> transformAliases = getList(TRANSFORMS_CONFIG); final List<Transformation<R>> transformations = new ArrayList<>(transformAliases.size()); for (String alias : transformAliases) { final String prefix = TRANSFORMS_CONFIG + "." + alias + "."; try { @SuppressWarnings("unchecked") final Transformation<R> transformation = Utils.newInstance(getClass(prefix + "type"), Transformation.class); Map<String, Object> configs = originalsWithPrefix(prefix); Object predicateAlias = configs.remove(PredicatedTransformation.PREDICATE_CONFIG); Object negate = configs.remove(PredicatedTransformation.NEGATE_CONFIG); transformation.configure(configs); if (predicateAlias != null) { String predicatePrefix = PREDICATES_PREFIX + predicateAlias + "."; @SuppressWarnings("unchecked") Predicate<R> predicate = Utils.newInstance(getClass(predicatePrefix + "type"), Predicate.class); predicate.configure(originalsWithPrefix(predicatePrefix)); transformations.add(new PredicatedTransformation<>(predicate, negate == null ? false : Boolean.parseBoolean(negate.toString()), transformation)); } else { transformations.add(transformation); } } catch (Exception e) { throw new ConnectException(e); } } return transformations; }
Source:
<code>public void onNewHead(FlowNode flowNode) { if (!isMonitored(flowNode)) { return; } StepEndNode endNode = (StepEndNode) flowNode; StepStartNode startNode = endNode.getStartNode(); int stage_depth = 0; for (BlockStartNode node : startNode.iterateEnclosingBlocks()) { if (isStageNode(node)) { stage_depth++; } } <START> DatadogClient client = ClientFactory.getClient(); <END> try { BuildData buildData = new BuildData(getRun(flowNode), flowNode.getExecution().getOwner().getListener()); String hostname = buildData.getHostname(""); Map<String, Set<String>> tags = buildData.getTags(); TagsUtil.addTagToTags(tags, "stage_name", getStageName(startNode)); TagsUtil.addTagToTags(tags, "stage_depth", String.valueOf(stage_depth)); tags.remove("result"); client.gauge("jenkins.job.stageduration", getTime(startNode, endNode), hostname, tags); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }</code><technical_language>In other places in code check if client is null first, do unneeded computation if client is null</technical_language>

Target:
public void onNewHead(FlowNode flowNode) { if (!isMonitored(flowNode)) { return; } DatadogClient client = ClientFactory.getClient(); if (client == null){ return; } StepEndNode endNode = (StepEndNode) flowNode; StepStartNode startNode = endNode.getStartNode(); int stageDepth = 0; String directParentName = null; for (BlockStartNode node : startNode.iterateEnclosingBlocks()) { if (isStageNode(node)) { if(directParentName == null){ directParentName = getStageName(node); } stageDepth++; } } if(directParentName == null){ directParentName = "root"; } WorkflowRun run = getRun(flowNode); if(run == null){ return; } try { BuildData buildData = new BuildData(run, flowNode.getExecution().getOwner().getListener()); String hostname = buildData.getHostname(""); Map<String, Set<String>> tags = buildData.getTags(); TagsUtil.addTagToTags(tags, "stage_name", getStageName(startNode)); TagsUtil.addTagToTags(tags, "parent_stage_name", directParentName); TagsUtil.addTagToTags(tags, "stage_depth", String.valueOf(stageDepth)); tags.remove("result"); client.gauge("jenkins.job.stage_duration", getTime(startNode, endNode), hostname, tags); } catch (IOException | InterruptedException e) { DatadogUtilities.severe(logger, e, "Unable to submit the stage duration metric for " + getStageName(startNode)); } }
Source:
<code>public void registerEntities() throws IOException { <START> OServerAdmin serverAdmin = new OServerAdmin(getConnectionUrl()).connect("root", "root"); <END> if (!serverAdmin.existsDatabase()) { logger.debug("Create database " + database); serverAdmin.createDatabase(database, "document", "plocal").close(); } factory().db().getEntityManager().registerEntityClasses(DOMAIN_PACKAGE); }</code><technical_language>@AlexOreshkevich, fields for username password here, effectively hard-coding here... I this a overlooked, do fields properties</technical_language>

Target:
public void registerEntities() throws IOException { OServerAdmin serverAdmin = new OServerAdmin(getConnectionUrl()).connect(user, password); if (!serverAdmin.existsDatabase()) { logger.debug("Create database " + database); serverAdmin.createDatabase(database, "document", "plocal").close(); } factory().db().getEntityManager().registerEntityClasses(DOMAIN_PACKAGE); }
Source:
<code><START> public void revokeAllRolesFor(String username) { <END> for (List<RoleUser> usersOfRole : roleToUsersMappings.values()) { usersOfRole.remove(new RoleUser(username)); } }</code><technical_language>removeUserFromAllRoles</technical_language>

Target:
public void revokeAllRolesFor(String username) { final RoleUser roleUser = new RoleUser(username); synchronized (roleToUsersMappings) { Set<PluginRoleConfig> pluginRoles = new HashSet<>(roleToUsersMappings.keySet()); for (PluginRoleConfig pluginRole : pluginRoles) { roleToUsersMappings.get(pluginRole).remove(roleUser); } } }
Source:
<code>public Double getDistance() { if (!isLeaf()) { throw new IllegalStateException("No target value exists for a logical operator"); } Object distance = json.get(DISTANCE); if (distance == null) { return null; <START> } else if (distance instanceof Double) { <END> return (Double) distance; } else if (distance instanceof Integer) { return ((Integer) distance).doubleValue(); } else if (distance instanceof Long) { return ((Long) distance).doubleValue(); } else { throw new IllegalStateException("The distance value could not be converted into a double"); } }</code><technical_language>Do need support three? I of thought Double suffice. Is JSON parser consistent</technical_language>

Target:
public Double getDistance() { if (!isLeaf()) { throw new IllegalStateException("No distance value exists for a logical operator"); } Object distance = json.get(DISTANCE); if (distance == null) { return null; } if (distance instanceof Number) { return ((Number) distance).doubleValue(); } throw new IllegalStateException("The distance value could not be converted into a double"); }
Source:
<code>public void createSubscription() throws Exception { <START> Subscription subscription = gd.getNotificationService().createSubscription(project, <END> gd.getAccountService().getCurrent(), new Subscription( Arrays.asList(new TimerEvent("0 * * * * *"), new TimerEvent("1 * * * * *")), new Condition("true"), new Template("test message"), Arrays.asList(channel.getMeta().getUri()), new Meta("test subscription"))); assertThat(subscription, is(notNullValue())); }</code><technical_language>add missing final</technical_language>

Target:
public void createSubscription() throws Exception { subscription = gd.getNotificationService().createSubscription(project, gd.getAccountService().getCurrent(), new Subscription( Arrays.asList(new TimerEvent("0 * * * * *"), new TimerEvent("1 * * * * *")), singletonList(channel), new TriggerCondition("true"), new MessageTemplate("test message"), "test subscription")); assertThat(subscription, is(notNullValue())); }
Source:
<code>private Callable<Boolean> getConnectAndLoginCallable() { return () -> { try { xmppConnection.connect(); } catch(Exception t) { logger.warn(MucClient.this + " error connecting", t); return true; } if (xmppConnection.isConnected()) { <START> xmppConnection.login(); <END> } else { logger.info(MucClient.this + " still not connected."); } return false; }; }</code><technical_language>login() potentially fail exception. simplify try { if (!xmppConnection.isConnected()) xmppConnnection.connect(); xmppConnection.login(); }</technical_language>

Target:
private Callable<Boolean> getConnectAndLoginCallable() { return () -> { try { if (!xmppConnection.isConnected()) { xmppConnection.connect(); } } catch(Exception t) { logger.warn(MucClient.this + " error connecting", t); return true; } logger.info("Logging in."); xmppConnection.login(); executor.shutdown(); return false; }; }
Source:
<code>@Test public void checkAbilityToUseNodeDefinedExplicitly() { <START> File node = new File("src/test/java/io/appium/java_client/service/local/appium.js"); <END> AppiumServiceBuilder builder = new AppiumServiceBuilder().withAppiumJS(node); assertThat(new File(builder.createArgs().get(0)).getAbsolutePath(), is(node.getAbsolutePath())); }</code><technical_language>magic string moved constants</technical_language>

Target:
@Test public void checkAbilityToUseNodeDefinedExplicitly() { File mainJS = PATH_T0_TEST_MAIN_JS.toFile(); AppiumServiceBuilder builder = new AppiumServiceBuilder() .withAppiumJS(mainJS); assertThat(builder.createArgs().get(0), is(mainJS.getAbsolutePath())); }
Source:
<code>public void shouldReturnNotFoundViolation() { Review review = new Review(ImmutableList.of(new ReviewFile("test"))); ReviewResult reviewResult = fixture.process(review); assertThat(reviewResult).isNotNull(); <START> assert reviewResult != null; <END> assertThat(reviewResult.getViolations()).isNotEmpty(); assertThat(reviewResult.getViolations()) .extracting("message") .containsOnly("File not found!"); }</code><technical_language>Haha, needed :)</technical_language>

Target:
public void shouldReturnNotFoundViolation() { Review review = new Review(ImmutableList.of(new ReviewFile("test"))); ReviewResult reviewResult = fixture.process(review); assertThat(reviewResult).isNotNull(); assertThat(reviewResult.getViolations()) .isNotEmpty() .extracting("message") .containsOnly("File not found!"); }
Source:
<code>public Object getValueAt(final int rowIndex, final int columnIndex) { final Column column = Column.values()[columnIndex]; final GameDescription description = gameList.get(rowIndex).getSecond(); switch (column) { case Host: return description.getHostName(); case Round: final int round = description.getRound(); return round == 0 ? "-" : String.valueOf(round); case Name: return description.getGameName(); case Players: return description.getPlayerCount(); case P: return (description.isPassworded() ? "*" : ""); case GV: return description.getGameVersion(); case Status: return description.getStatus(); case Comments: return description.getComment(); case Started: return description.getFormattedBotStartTime(); case GUID: return gameList.get(rowIndex).getFirst(); default: <START> throw new IllegalStateException("Unknown column:" + column); <END> } }</code><technical_language>wanted point out throw AssertionError impossible conditions</technical_language>

Target:
public Object getValueAt(final int rowIndex, final int columnIndex) { final Column column = Column.values()[columnIndex]; final GameDescription description = gameListModel.getGameDescriptionByRow(rowIndex); switch (column) { case Host: return description.getHostName(); case Round: final int round = description.getRound(); return round == 0 ? "-" : String.valueOf(round); case Name: return description.getGameName(); case Players: return description.getPlayerCount(); case P: return (description.isPassworded() ? "*" : ""); case GV: return description.getGameVersion(); case Status: return description.getStatus(); case Comments: return description.getComment(); case Started: return description.getFormattedBotStartTime(); case GUID: return gameListModel.getGameGuidByRow(rowIndex); default: throw new IllegalStateException("Unknown column:" + column); } }
Source:
<code>public Set<Expr> getScalarInputs(List<Expr> args) { <START> return ImmutableSet.of(args.get(1), args.get(2)); <END> }</code><technical_language>this check if args length is 2 3</technical_language>

Target:
public Set<Expr> getScalarInputs(List<Expr> args) { if (args.size() == 3) { return ImmutableSet.of(args.get(1), args.get(2)); } else { return ImmutableSet.of(args.get(1)); } }
Source:
<code>private String retrieveVcfSection(String vcfFilePath) throws IOException { String vcfSection = ""; int lineCount = NUMBER_OF_LINES; Scanner scanner = new Scanner(new GZIPInputStream(new FileInputStream(vcfFilePath))); <START> while (scanner.hasNextLine()) { <END> String line = scanner.nextLine(); if (!line.startsWith("#")) { lineCount--; vcfSection += line + "\n"; if (lineCount == 0) { break; } } } scanner.close(); if (lineCount > 0) { return ""; } return vcfSection; }</code><technical_language>Making this java while (scanner.hasNextLine() && lineCount > 0) { removing break a bit more clear loop stop</technical_language>

Target:
private String retrieveVcfSection(String vcfFilePath) throws IOException { String vcfSection = ""; int lineCount = NUMBER_OF_LINES; Scanner scanner = new Scanner(new GZIPInputStream(new FileInputStream(vcfFilePath))); while (scanner.hasNextLine() && lineCount > 0) { String line = scanner.nextLine(); if (!line.startsWith("#")) { lineCount--; vcfSection += line + "\n"; } } scanner.close(); if (lineCount > 0) { return ""; } return vcfSection; }
Source:
<code>public boolean isClientAwake(Registration registration) { <START> return clientPrecenses.get(registration.getEndpoint()) != null; <END> }</code><technical_language>containsKey()</technical_language>

Target:
public boolean isClientAwake(Registration registration) { return clientPresences.containsKey(registration.getEndpoint()); }
Source:
<code>public void changePasswordAsAdmin(CommandSender sender, final String playerName, String newPassword) { final String lowerCaseName = playerName.toLowerCase(); if (!(playerCache.isAuthenticated(lowerCaseName) || dataSource.isAuthAvailable(lowerCaseName))) { if (sender == null) { ConsoleLogger.warning("Tried to change password for user " + lowerCaseName + " but it doesn't exist!"); } else { commonService.send(sender, MessageKey.UNKNOWN_USER); } return; } HashedPassword hashedPassword = passwordSecurity.computeHash(newPassword, lowerCaseName); if (dataSource.updatePassword(lowerCaseName, hashedPassword)) { if (dataSource instanceof CacheDataSource) { bungeeSender.sendAuthMeBungeecordMessage(MessageType.REFRESH_PASSWORD, lowerCaseName); <START> } <END> if (sender != null) { commonService.send(sender, MessageKey.PASSWORD_CHANGED_SUCCESS); ConsoleLogger.info(sender.getName() + " changed password of " + lowerCaseName); } else { ConsoleLogger.info("Changed password of " + lowerCaseName); } } else { if (sender != null) { commonService.send(sender, MessageKey.ERROR); } ConsoleLogger.warning("An error occurred while changing password for user " + lowerCaseName + "!"); } }</code><technical_language>1) more elegant bungee sender care of checking if statement. method named accordingly. 2) introduce a method DataSource for this? boolean isCached() boolean hasCache()</technical_language>

Target:
public void changePasswordAsAdmin(CommandSender sender, final String playerName, String newPassword) { final String lowerCaseName = playerName.toLowerCase(); if (!(playerCache.isAuthenticated(lowerCaseName) || dataSource.isAuthAvailable(lowerCaseName))) { if (sender == null) { ConsoleLogger.warning("Tried to change password for user " + lowerCaseName + " but it doesn't exist!"); } else { commonService.send(sender, MessageKey.UNKNOWN_USER); } return; } HashedPassword hashedPassword = passwordSecurity.computeHash(newPassword, lowerCaseName); if (dataSource.updatePassword(lowerCaseName, hashedPassword)) { bungeeSender.sendAuthMeBungeecordMessage(MessageType.REFRESH_PASSWORD, lowerCaseName); if (sender != null) { commonService.send(sender, MessageKey.PASSWORD_CHANGED_SUCCESS); ConsoleLogger.info(sender.getName() + " changed password of " + lowerCaseName); } else { ConsoleLogger.info("Changed password of " + lowerCaseName); } } else { if (sender != null) { commonService.send(sender, MessageKey.ERROR); } ConsoleLogger.warning("An error occurred while changing password for user " + lowerCaseName + "!"); } }
Source:
<code>public String getId() { <START> return "PositionedCrop.com.bumptech.glide.load.resource.bitmap.x:" + xPercentage + ".y:" + yPercentage; <END> }</code><technical_language>x .y part of package name. I "...bitmap(x=..., y=....), for example...bitmap.x:0.0.y:0.0 dots</technical_language>

Target:
public String getId() { return "PositionedCrop.com.bumptech.glide.load.resource.bitmap(x=" + xPercentage + ",y=" + yPercentage + ")"; }
Source:
<code>public void initTable(final ImmutableList<String> columnHeads) { this.columnCount = columnHeads.size(); <START> DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); <END> this.header = new ASCIITableHeader[this.columnCount]; for (int i = 0; i < this.columnCount; i++) { header[i] = new ASCIITableHeader(columnHeads.get(i), ASCIITable.ALIGN_LEFT); } }</code><technical_language>This done in a static constructor</technical_language>

Target:
public void initTable(final ImmutableList<String> columnHeads) { this.columnCount = columnHeads.size(); this.header = new ASCIITableHeader[this.columnCount]; for (int i = 0; i < this.columnCount; i++) { header[i] = new ASCIITableHeader(columnHeads.get(i), ASCIITable.ALIGN_LEFT); } }
Source:
<code>public void getPackagesFromFile_shouldSkipOptionalFoldersIfJarFile() throws IOException{ File f = new File(this.getClass().getResource("/org/openmrs/module/include/test1-1.0-SNAPSHOT.omod").getFile()); <START> File d = new File("/tmp/test1-1.0-SNAPSHOT.jar"); <END> FileUtils.copyFile(f, d); Collection<String> packageCollection = ModuleUtil.getPackagesFromFile(d); Assert.assertFalse(packageCollection.isEmpty()); for (String string : packageCollection) { Assert.assertFalse(string.contains("lib")); Assert.assertFalse(string.contains("META-INF")); Assert.assertFalse(string.contains("web.module")); } }</code><technical_language>operating system run tests</technical_language>

Target:
public void getPackagesFromFile_shouldSkipOptionalFoldersIfJarFile() throws IOException{ File f = new File(this.getClass().getResource("/org/openmrs/module/include/test1-1.0-SNAPSHOT.omod").getFile()); File d = new File("/tmp/test1-1.0-SNAPSHOT.jar"); FileUtils.copyFile(f, d); Collection<String> packageCollection = ModuleUtil.getPackagesFromFile(d); Assert.assertFalse(packageCollection.isEmpty()); for (String string : packageCollection) { Assert.assertFalse(string.contains("lib")); Assert.assertFalse(string.contains("META-INF")); Assert.assertFalse(string.contains("web/module")); } }
Source:
<code>public void initialise() { message = find("message", UILabel.class); message.bindText(new ReadOnlyBinding<String>() { @Override public String get() { Iterable<Message> msgs = console.getMessages(CoreMessageType.CHAT, CoreMessageType.NOTIFICATION); ArrayList<Message> msgsList = new ArrayList<>(); StringBuilder messageHistory = new StringBuilder(); for (Message msg : msgs) { msgsList.add(msg); } for (int i = msgsList.size() >= MAX_LINES ? msgsList.size() - MAX_LINES : 0; i < msgsList.size(); i++) { messageHistory.append(msgsList.get(i).getMessage()); if (i < msgsList.size() - 1) { messageHistory.append(Console.NEW_LINE); } } <START> return messageHistory.toString(); <END> } }); }</code><technical_language>sounds preferable copying entire buffer pruning copy n messages afterwards</technical_language>

Target:
public void initialise() { message = find("message", UILabel.class); message.bindText(new ReadOnlyBinding<String>() { @Override public String get() { Iterable<Message> msgs = console.getMessages(CoreMessageType.CHAT, CoreMessageType.NOTIFICATION); StringBuilder messageHistory = new StringBuilder(); int count = 1; int size = Iterables.size(msgs); for (Message msg : msgs) { if (count > size - MAX_MESSAGES) { messageHistory.append(msg.getMessage()); if (count < size) { messageHistory.append(Console.NEW_LINE); } } count++; } return messageHistory.toString(); } }); }
Source:
<code>public void execute(JobExecutionContext context) throws JobExecutionException { Logger.debug(this, "Running ContentReviewThread - " + new Date()); try { run(); } catch (Exception e) { Logger.info(this, e.toString()); } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.warn(this, e.getMessage(), e); <START> } <END> } }</code><technical_language>Remove entire wrapper finally block</technical_language>

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { Logger.debug(this, "Running ContentReviewThread - " + new Date()); try { run(); } catch (Exception e) { Logger.info(this, e.toString()); } }
Source:
<code><START> protected FilterBoxService(List<LanguageClient> clients) { <END> this.input = new String(); this.clients = clients; }</code><technical_language>a list</technical_language>

Target:
protected FilterBoxService(List<LanguageClient> clients) { fInput = new String(); fClients = clients; }
Source:
<code>private void setDiskImageSnapshotType(Map<Guid, DiskImage> diskImageMap, Snapshot snapshot) { DiskImage <START> d = <END> diskImageMap.get(snapshot.getId()); if ( d == null ) { return; } if (snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW) { d.setActive(true); } else if (snapshot.getType() == SnapshotType.REGULAR) { d.setActive(false); } }</code><technical_language>diskImage</technical_language>

Target:
private void setDiskImageSnapshotType(Map<Guid, DiskImage> diskImageMap, Snapshot snapshot) { DiskImage diskImage = diskImageMap.get(snapshot.getId()); if ( diskImage == null ) { return; } if (snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW) { diskImage.setActive(true); } else if (snapshot.getType() == SnapshotType.REGULAR) { diskImage.setActive(false); } }
Source:
<code>protected void throwIfWriteAlreadyCommitted(TableReference tableRef, Map<Cell, byte[]> writes, ConflictHandler conflictHandler, LockToken commitLocksToken, TransactionService transactionService) throws TransactionConflictException { if (writes.isEmpty() || !conflictHandler.checkWriteWriteConflicts()) { return; } Set<CellConflict> spanningWrites = Sets.newHashSet(); Set<CellConflict> dominatingWrites = Sets.newHashSet(); Map<Cell, Long> keysToLoad = Maps.asMap(writes.keySet(), Functions.constant(Long.MAX_VALUE)); while (!keysToLoad.isEmpty()) { keysToLoad = detectWriteAlreadyCommittedInternal( tableRef, keysToLoad, spanningWrites, dominatingWrites, transactionService); } if (conflictHandler == ConflictHandler.RETRY_ON_VALUE_CHANGED) { throwIfValueChangedConflict(tableRef, writes, spanningWrites, dominatingWrites, commitLocksToken); <START> } else if (conflictHandler.checkWriteWriteConflicts()) { <END> if (!spanningWrites.isEmpty() || !dominatingWrites.isEmpty()) { getTransactionConflictsMeter().mark(); throw TransactionConflictException.create(tableRef, getStartTimestamp(), spanningWrites, dominatingWrites, System.currentTimeMillis() - timeCreated); } } else { throw new IllegalArgumentException("Unknown conflictHandler type: " + conflictHandler); } }</code><technical_language>some simplification do - notably this is true</technical_language>

Target:
protected void throwIfWriteAlreadyCommitted(TableReference tableRef, Map<Cell, byte[]> writes, ConflictHandler conflictHandler, LockToken commitLocksToken, TransactionService transactionService) throws TransactionConflictException { if (writes.isEmpty() || !conflictHandler.checkWriteWriteConflicts()) { return; } Set<CellConflict> spanningWrites = Sets.newHashSet(); Set<CellConflict> dominatingWrites = Sets.newHashSet(); Map<Cell, Long> keysToLoad = Maps.asMap(writes.keySet(), Functions.constant(Long.MAX_VALUE)); while (!keysToLoad.isEmpty()) { keysToLoad = detectWriteAlreadyCommittedInternal( tableRef, keysToLoad, spanningWrites, dominatingWrites, transactionService); } if (conflictHandler == ConflictHandler.RETRY_ON_VALUE_CHANGED) { throwIfValueChangedConflict(tableRef, writes, spanningWrites, dominatingWrites, commitLocksToken); } else { if (!spanningWrites.isEmpty() || !dominatingWrites.isEmpty()) { getTransactionConflictsMeter().mark(); throw TransactionConflictException.create(tableRef, getStartTimestamp(), spanningWrites, dominatingWrites, System.currentTimeMillis() - timeCreated); } } }
Source:
<code>public boolean clear(String hostname) { return resolveCache.clear( appendDot( <START> checkNotNull(hostname, "hostname"))); <END> }</code><technical_language>nit: merge lines formatting a bit strange</technical_language>

Target:
public boolean clear(String hostname) { checkNotNull(hostname, "hostname"); return resolveCache.clear(appendDot(hostname)); }
Source:
<code>public void initialize() { logger.debug("Initializing the MeteoBlue handler..."); bridge = getBridge(); if (bridge == null) { logger.warn("Unable to initialize meteoblue. No bridge was configured."); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Bridge not configured."); return; } MeteoBlueConfiguration config = getConfigAs(MeteoBlueConfiguration.class); if (StringUtils.isBlank(config.serviceType)) { <START> flagBadConfig("The serviceType setting was not configured."); <END> return; } if (StringUtils.isBlank(config.location)) { flagBadConfig("The location setting was not configured."); return; } config.parseLocation(); if (config.latitude == null) { flagBadConfig(String.format("Could not determine latitude from the defined location setting (%s).", config.location)); return; } if (config.latitude > 90.0 || config.latitude < -90.0) { flagBadConfig(String.format("Specified latitude value (%d) is not valid.", config.latitude)); return; } if (config.longitude == null) { flagBadConfig(String.format("Could not determine longitude from the defined location setting (%s).", config.location)); return; } if (config.longitude > 180.0 || config.longitude < -180.0) { flagBadConfig(String.format("Specified longitude value (%d) is not valid.", config.longitude)); return; } updateStatus(ThingStatus.ONLINE); startAutomaticRefresh(config); properlyConfigured = true; }</code><technical_language>default in this case continue</technical_language>

Target:
public void initialize() { logger.debug("Initializing the meteoblue handler..."); bridge = getBridge(); if (bridge == null) { logger.warn("Unable to initialize meteoblue. No bridge was configured."); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Bridge not configured."); return; } MeteoBlueConfiguration config = getConfigAs(MeteoBlueConfiguration.class); if (StringUtils.isBlank(config.serviceType)) { config.serviceType = MeteoBlueConfiguration.SERVICETYPE_NONCOMM; logger.debug("Using default service type ({}).", config.serviceType); return; } if (StringUtils.isBlank(config.location)) { flagBadConfig("The location was not configured."); return; } config.parseLocation(); if (config.latitude == null) { flagBadConfig(String.format("Could not determine latitude from the defined location setting (%s).", config.location)); return; } if (config.latitude > 90.0 || config.latitude < -90.0) { flagBadConfig(String.format("Specified latitude value (%d) is not valid.", config.latitude)); return; } if (config.longitude == null) { flagBadConfig(String.format("Could not determine longitude from the defined location setting (%s).", config.location)); return; } if (config.longitude > 180.0 || config.longitude < -180.0) { flagBadConfig(String.format("Specified longitude value (%d) is not valid.", config.longitude)); return; } updateStatus(ThingStatus.UNKNOWN); startAutomaticRefresh(config); properlyConfigured = true; }