auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void getTokenFromBrowserIDAssertion(final String assertion, final boolean conditionsAccepted, final TokenServerClientDelegate delegate) { final BaseResource r = new BaseResource(uri); r.delegate = new BaseResourceDelegate(r) { @Override public void handleHttpResponse(HttpResponse response) { SkewHandler skewHandler = SkewHandler.getSkewHandlerForResource(r); <START> if (skewHandler != null) { <END> skewHandler.updateSkew(response, System.currentTimeMillis()); } try { TokenServerToken token = processResponse(response); invokeHandleSuccess(delegate, token); } catch (TokenServerException e) { invokeHandleFailure(delegate, e); } } @Override public void handleTransportException(GeneralSecurityException e) { invokeHandleError(delegate, e); } @Override public void handleHttpProtocolException(ClientProtocolException e) { invokeHandleError(delegate, e); } @Override public void handleHttpIOException(IOException e) { invokeHandleError(delegate, e); } @Override public AuthHeaderProvider getAuthHeaderProvider() { return new BrowserIDAuthHeaderProvider(assertion); } @Override public void addHeaders(HttpRequestBase request, DefaultHttpClient client) { String host = request.getURI().getHost(); request.setHeader(new BasicHeader("Host", host)); if (conditionsAccepted) { request.addHeader("X-Conditions-Accepted", "1"); } } }; r.get(); }</code><technical_language>This null, checking implies</technical_language>

Target:
public void getTokenFromBrowserIDAssertion(final String assertion, final boolean conditionsAccepted, final TokenServerClientDelegate delegate) { final BaseResource r = new BaseResource(uri); r.delegate = new BaseResourceDelegate(r) { @Override public void handleHttpResponse(HttpResponse response) { SkewHandler skewHandler = SkewHandler.getSkewHandlerForResource(r); skewHandler.updateSkew(response, System.currentTimeMillis()); try { TokenServerToken token = processResponse(response); invokeHandleSuccess(delegate, token); } catch (TokenServerException e) { invokeHandleFailure(delegate, e); } } @Override public void handleTransportException(GeneralSecurityException e) { invokeHandleError(delegate, e); } @Override public void handleHttpProtocolException(ClientProtocolException e) { invokeHandleError(delegate, e); } @Override public void handleHttpIOException(IOException e) { invokeHandleError(delegate, e); } @Override public AuthHeaderProvider getAuthHeaderProvider() { return new BrowserIDAuthHeaderProvider(assertion); } @Override public void addHeaders(HttpRequestBase request, DefaultHttpClient client) { String host = request.getURI().getHost(); request.setHeader(new BasicHeader("Host", host)); if (conditionsAccepted) { request.addHeader("X-Conditions-Accepted", "1"); } } }; r.get(); }
Source:
<code>private JobPrefixFile(final Path file, final FileChannel channel, final FileLock lock) throws IOException, IllegalStateException { <START> Preconditions.checkNotNull(file); <END> Preconditions.checkNotNull(channel); Preconditions.checkNotNull(lock); this.file = file; this.prefix = file.getFileName().toString(); this.channel = channel; this.lock = lock; }</code><technical_language>I inline checkNotNull assignment. This is easier null check omitted for some assignment. provide variable names checkNotNull. java this.file = checkNotNull(file, "file"); ..</technical_language>

Target:
private JobPrefixFile(final Path file, final FileChannel channel, final FileLock lock) throws IOException, IllegalStateException { this.file = Preconditions.checkNotNull(file, "file"); this.channel = Preconditions.checkNotNull(channel, "channel"); this.lock = Preconditions.checkNotNull(lock, "lock"); this.prefix = file.getFileName().toString(); }
Source:
<code>public void testDelayTaskCompleted() { final Task<Integer> task = Task.callable(() -> 1234); final Task<Integer> taskWithDelay = task.withDelay(200, TimeUnit.MILLISECONDS); assertEquals(1234, runAndWait(taskWithDelay).intValue()); assertTrue(task.isDone()); assertTrue(taskWithDelay.isDone()); assertFalse(task.isFailed()); assertFalse(taskWithDelay.isFailed()); long taskWithDelayStartTimeMillis = TimeUnit.MILLISECONDS.convert(taskWithDelay.getShallowTrace().getStartNanos(), TimeUnit.NANOSECONDS); long taskStartTimeMillis = TimeUnit.MILLISECONDS.convert(task.getShallowTrace().getStartNanos(), TimeUnit.NANOSECONDS); <START> assertTrue(taskStartTimeMillis - taskWithDelayStartTimeMillis >= 200); <END> }</code><technical_language>This flaky tests, ctx.createTimer internally ScheduledExeuctorService, get exact precision want</technical_language>

Target:
public void testDelayTaskCompleted() throws InterruptedException { final Task<Integer> task = Task.callable(() -> 1234); final Task<Integer> taskWithDelay = task.withDelay(1, TimeUnit.SECONDS); getEngine().run(taskWithDelay); taskWithDelay.await(200, TimeUnit.MILLISECONDS); assertFalse(taskWithDelay.isDone()); assertFalse(task.isDone()); taskWithDelay.await(3, TimeUnit.SECONDS); assertTrue(taskWithDelay.isDone()); assertTrue(task.isDone()); assertFalse(task.isFailed()); assertFalse(taskWithDelay.isFailed()); assertEquals(1234, taskWithDelay.get().intValue()); }
Source:
<code>public static Locale parseLocale(final String localeString) { if ((localeString != null) && (localeString.length() != 0)) { final int index = localeString.indexOf("_"); final int index2 = localeString.indexOf("_", index + 1); <START> Locale l; <END> if (index == -1) { l = new Locale(localeString); } else if (index2 == -1) { l = new Locale(localeString.substring(0, index), localeString.substring(index + 1)); } else { l = new Locale(localeString.substring(0, index), localeString.substring(index + 1, index2), localeString.substring(index2 + 1)); } return l; } return null; }</code><technical_language>prefer more descriptive variable names - change this "locale", equally descriptive please</technical_language>

Target:
public static Locale parseLocale(final String localeString) { if ((localeString != null) && (localeString.length() != 0)) { final int index = localeString.indexOf("_"); final int index2 = localeString.indexOf("_", index + 1); Locale resultLocale; if (index == -1) { resultLocale = new Locale(localeString); } else if (index2 == -1) { resultLocale = new Locale(localeString.substring(0, index), localeString.substring(index + 1)); } else { resultLocale = new Locale( localeString.substring(0, index), localeString.substring(index + 1, index2), localeString.substring(index2 + 1)); } return resultLocale; } return null; }
Source:
<code>public List<Property> properties() { List<Property> properties = new ArrayList<>(); if (binaryAnnotations != null) { Set<String> services = new HashSet<>(); for (BinaryAnnotation binaryAnnotation : binaryAnnotations) { <START> Property property = new Property(binaryAnnotation.getKey(), binaryAnnotation.getValue()); <END> Endpoint endpoint = binaryAnnotation.getEndpoint(); if (endpoint != null && !services.contains(endpoint.getServiceName())) { properties.add(new Property("service", endpoint.getServiceName(), PropertyType.Text)); services.add(endpoint.getServiceName()); } properties.add(property); } } return properties; }</code><technical_language>need provide property type. a mapping <LINK_0> PropertyType enum values. Currently need detailed - listed numeric - create additional PropertyType values for Boolean Binary? Default String</technical_language>

Target:
public List<Property> properties() { if (binaryAnnotations == null || binaryAnnotations.isEmpty()) { return Collections.emptyList(); } List<Property> properties = new ArrayList<>(); Set<Endpoint> endpoints = new HashSet<>(); for (BinaryAnnotation binaryAnnotation : binaryAnnotations) { properties.add(new Property(binaryAnnotation.getKey(), binaryAnnotation.getValue(), AnnotationTypeUtil.toPropertyType(binaryAnnotation.getType()))); if (binaryAnnotation.getEndpoint() != null) { Endpoint endpoint = binaryAnnotation.getEndpoint(); if (endpoints.isEmpty()) { properties.add(new Property("service", endpoint.getServiceName())); properties.add(new Property("ipv4", endpoint.getIpv4())); } else if (!endpoints.contains(endpoint)){ log.severe("Multiple Endpoints within one Span: " + endpoint); } endpoints.add(endpoint); } } return properties; }
Source:
<code>private void validateForRequireDrug(Errors errors, DrugOrder order) { boolean requireDrug = Context.getAdministrationService().getGlobalPropertyValue( OpenmrsConstants.GLOBAL_PROPERTY_DRUG_ORDER_REQUIRE_DRUG, false); OrderService orderService = Context.getOrderService(); if (order.isNonCodedDrug()) { if (OpenmrsUtil.nullSafeEquals(orderService.getNonCodedDrugConcept(), order.getConcept())) { ValidationUtils.rejectIfEmpty(errors, "drugNonCoded", "DrugOrder.error.drugNonCodedIsRequired"); } if (order.getDrug() != null) { <START> errors.rejectValue("drug", "DrugOrder.error.onlyOneOfDrugOrNonCodedShouldBeSet"); <END> } } else { if (requireDrug) { ValidationUtils.rejectIfEmpty(errors, "drug", "DrugOrder.error.drugIsRequired"); } if (OpenmrsUtil.nullSafeEquals(orderService.getNonCodedDrugConcept(), order.getConcept())) { errors.rejectValue("concept", "DrugOrder.error.cannotSetBothDrugAndNonCodedDrug"); } } }</code><technical_language>This correct, need fetch active drug order of patient, loop find drug other orders compare coded this drug's coded</technical_language>

Target:
private void validateForRequireDrug(Errors errors, DrugOrder order) { boolean requireDrug = Context.getAdministrationService().getGlobalPropertyValue( OpenmrsConstants.GLOBAL_PROPERTY_DRUG_ORDER_REQUIRE_DRUG, false); OrderService orderService = Context.getOrderService(); if(requireDrug){ if(order.getConcept() != null && OpenmrsUtil.nullSafeEquals(orderService.getNonCodedDrugConcept(), order.getConcept())){ if(order.getDrug() == null && !order.isNonCodedDrug()){ errors.rejectValue("drugNonCoded", "DrugOrder.error.drugNonCodedIsRequired"); } else if(order.getDrug() != null){ errors.rejectValue("concept", "DrugOrder.error.onlyOneOfDrugOrNonCodedShouldBeSet"); } }else{ if(order.getDrug() == null && !order.isNonCodedDrug()){ errors.rejectValue("drug", "DrugOrder.error.drugIsRequired"); } else if(order.getDrug() != null && order.isNonCodedDrug()){ errors.rejectValue("concept", "DrugOrder.error.onlyOneOfDrugOrNonCodedShouldBeSet"); } } } }
Source:
<code>private Task<? extends Serializable> createDbTask(Database dbObj) { CreateDatabaseDesc createDbDesc = new CreateDatabaseDesc(dbObj.getName(), dbObj.getDescription(), null, false, <START> updateDbProps(dbObj, context.dumpDirectory, true)); <END> DDLWork2 work = new DDLWork2(new HashSet<>(), new HashSet<>(), createDbDesc); return TaskFactory.get(work, context.hiveConf); }</code><technical_language>parameter bee removed</technical_language>

Target:
private Task<? extends Serializable> createDbTask(Database dbObj) { CreateDatabaseDesc createDbDesc = new CreateDatabaseDesc(dbObj.getName(), dbObj.getDescription(), null, false, updateDbProps(dbObj, context.dumpDirectory)); DDLWork2 work = new DDLWork2(new HashSet<>(), new HashSet<>(), createDbDesc); return TaskFactory.get(work, context.hiveConf); }
Source:
<code>public void templateClassification_createTemplateAndChangeItsType() { TemplatePage templatePage = new TemplatePage(); TemplateClassification templateClassification = templatePage .createTemplate(this.templateName) .open(this.templateName) .getTemplateClassification(); <START> templateClassification <END> .open() .resetTemplateType() .save(); Assertion.assertTrue(templateName.equals("Unknown"), "Template type was reset"); PageObjectLogging.logInfo("Template type was reset"); templateClassification .open() .changeTemplateType("Infobox") .save(); String templateType = templateClassification.getTemplateType(); Assertion.assertTrue(templateType.equals("Infobox"), "Template type set to Infobox"); PageObjectLogging.logInfo("Template type set to: '" + templateType + "'"); templateClassification .open() .changeTemplateType("Quote") .save(); String oldTemplateType = templateType; String currentTemplateType = templateClassification.getTemplateType(); Assertion.assertFalse(currentTemplateType.equals(oldTemplateType), "Template type did not change"); PageObjectLogging.logInfo( "Template type changed from: '" + oldTemplateType + "', to: '" + currentTemplateType + "'"); }</code><technical_language>chain this L28</technical_language>

Target:
public void templateClassification_createTemplateAndChangeItsType() { TemplatePage templatePage = new TemplatePage() .createTemplate(DEFAULT_TEMPLATE_NAME) .open(DEFAULT_TEMPLATE_NAME); TemplateClassification templateClassification = templatePage.getTemplateClassification(); templateClassification .open() .resetTemplateType() .save(); String oldTemplateType = templateClassification.getTemplateType(); Assertion.assertEquals(templateClassification.getTemplateType(), TemplateTypes.UNKNOWN.getType()); templateClassification .open() .changeTemplateType(TemplateTypes.INFOBOX) .save(); Assertion.assertEquals(templateClassification.getTemplateType(), TemplateTypes.INFOBOX.getType()); templateClassification .open() .changeTemplateType(TemplateTypes.QUOTE) .save(); String currentTemplateType = templateClassification.getTemplateType(); Assertion.assertNotEquals(currentTemplateType, oldTemplateType); }
Source:
<code>public boolean deleteAddress() { if (selectedAddress != null) { return loadTestDataService.deleteAddress(selectedAddress); } else { <START> addPatientErrorMessages("Address have to be select to be deleted"); <END> } return false; }</code><technical_language>Refactor save code GenericDAO remove redundant logic</technical_language>

Target:
public boolean deleteAddress() { boolean result = false; if (selectedAddress != null) { result = loadTestDataService.deleteAddress(selectedAddress); } else { addPatientErrorMessages(msgForSelectDelete("address")); } return result; }
Source:
<code>EJBRootContext(final NamingProvider namingProvider, final FastHashtable<String, Object> env) { super(env); this.namingProvider = namingProvider; URI clusterAffinity = getClusterAffinityURIFromEnvironment(); if (clusterAffinity != null) { <START> affinity = Affinity.forUri(clusterAffinity); <END> } else { final URI providerUri = namingProvider == null ? null : namingProvider.getProviderUri(); if (providerUri == null) { affinity = Affinity.NONE; } else { final String scheme = providerUri.getScheme(); if (scheme == null) { affinity = Affinity.NONE; } else { affinity = Affinity.forUri(providerUri); } } } }</code><technical_language>..this accept a cluster name, a URI, (public) ClusterAffinity(String) constructor</technical_language>

Target:
EJBRootContext(final NamingProvider namingProvider, final FastHashtable<String, Object> env) { super(env); this.namingProvider = namingProvider; String clusterName = getClusterAffinityValueFromEnvironment(); if (clusterName != null) { affinity = new ClusterAffinity(clusterName); } else { final URI providerUri = namingProvider == null ? null : namingProvider.getProviderUri(); if (providerUri == null) { affinity = Affinity.NONE; } else { final String scheme = providerUri.getScheme(); if (scheme == null) { affinity = Affinity.NONE; } else { affinity = Affinity.forUri(providerUri); } } } }
Source:
<code>public Plugin create(String id, Plugin plugin) { plugin.setLastModified(System.currentTimeMillis()); <START> Assert.notNull(plugin.getName(), "Plugin name must NOT be null!"); <END> Assert.notNull(plugin.getNamespace(), "Plugin namespace must NOT be null!"); Assert.notNull(plugin.getDescription(), "Plugin description must NOT be null!"); Assert.notNull(plugin.getAuthor(), "Plugin author must NOT be null!"); Assert.notNull(plugin.getVersion(), "Plugin version must NOT be null!"); Assert.notNull(plugin.getDependencies(), "Plugin dependencies must NOT be null!"); Assert.notNull(plugin.getRequiredVersions(), "Plugin requiredVersions must NOT be null!"); Assert.notNull(plugin.getCapabilities(), "Plugin capabilities must NOT be null!"); update(id, plugin); return findById(id); }</code><technical_language>prefer Objects.requireNonNull (same functionality, jdk native)</technical_language>

Target:
public Plugin create(String id, Plugin plugin) { plugin.setLastModified(System.currentTimeMillis()); try { Objects.requireNonNull(plugin.getName(), "Plugin name must NOT be null!"); Objects.requireNonNull(plugin.getNamespace(), "Plugin namespace must NOT be null!"); Objects.requireNonNull(plugin.getDescription(), "Plugin description must NOT be null!"); Objects.requireNonNull(plugin.getAuthor(), "Plugin author must NOT be null!"); Objects.requireNonNull(plugin.getVersion(), "Plugin version must NOT be null!"); Objects.requireNonNull(plugin.getDependencies(), "Plugin dependencies must NOT be null!"); Objects.requireNonNull( plugin.getRequiredVersions(), "Plugin requiredVersions must NOT be null!"); Objects.requireNonNull(plugin.getCapabilities(), "Plugin capabilities must NOT be null!"); } catch (NullPointerException e) { throw new IllegalArgumentException(e.getMessage(), e); } update(id, plugin); return findById(id); }
Source:
<code>public void run() throws Exception { response = false; MultiMapContainer container = getOrCreateContainerWithoutAccess(); MultiMapValue multiMapValue = container.getMultiMapValueOrNull(dataKey); if (multiMapValue == null) { return; } Collection<MultiMapRecord> coll = multiMapValue.getCollection(false); MultiMapRecord record = new MultiMapRecord(isBinary() ? value : toObject(value)); <START> response = coll.remove(record); <END> }</code><technical_language>leave this part in: java if (coll.isEmpty()) { container.delete(dataKey); }</technical_language>

Target:
public void run() throws Exception { response = false; MultiMapContainer container = getOrCreateContainerWithoutAccess(); MultiMapValue multiMapValue = container.getMultiMapValueOrNull(dataKey); if (multiMapValue == null) { return; } Collection<MultiMapRecord> coll = multiMapValue.getCollection(false); MultiMapRecord record = new MultiMapRecord(isBinary() ? value : toObject(value)); response = coll.remove(record); if (coll.isEmpty()) { container.delete(dataKey); } }
Source:
<code>public void shouldRightProjectionOrElseRightProjection() { final RightProjection<Object, Integer> rightRight = Either.right(1).right(); <START> final RightProjection<Object, Integer> leftRight = Either.<Object, Integer>left(1).right(); <END> final RightProjection<Object, Integer> rightProjection = Either.right(2).right(); assertThat(rightRight.orElse(rightProjection).get()).isEqualTo(1); assertThat(leftRight.orElse(rightProjection).get()).isEqualTo(2); }</code><technical_language>this simplified, other</technical_language>

Target:
public void shouldRightProjectionOrElseRightProjection() { final RightProjection<Integer, Integer> elseProjection = API.<Integer, Integer>Right(2).right(); assertThat(Right(1).right().orElse(elseProjection).get()).isEqualTo(1); assertThat(Left(1).right().orElse(elseProjection).get()).isEqualTo(2); }
Source:
<code>public BasicLocationDefinition(String id, String name, String spec, Map<String,? extends Object> config) { <START> this.id = id != null ? id : LanguageUtils.newUid(); <END> this.name = name; this.spec = Preconditions.checkNotNull(spec); this.config = config==null ? ImmutableMap.<String, Object>of() : ImmutableMap.<String, Object>copyOf(config); }</code><technical_language>Do want LocationDefinition generate id if null is passed in? hide some programming errors. If want it, overload constructor a version id parameter</technical_language>

Target:
public BasicLocationDefinition(String id, String name, String spec, Map<String,? extends Object> config) { this.id = Preconditions.checkNotNull(id); this.name = name; this.spec = Preconditions.checkNotNull(spec); this.config = config==null ? ImmutableMap.<String, Object>of() : ImmutableMap.<String, Object>copyOf(config); }
Source:
<code>protected static double getColumnWidth(String columnId) { switch (columnId) { <START> case "Index": <END> return 70; case "Description": return 230; default: return 150; } }</code><technical_language>ExpressionIdentifier.INDEX.getName() WDYT</technical_language>

Target:
protected static double getColumnWidth(String columnId) { ExpressionIdentifier.NAME expressionName = ExpressionIdentifier.NAME.Other; try { expressionName = ExpressionIdentifier.NAME.valueOf(columnId); } catch (IllegalArgumentException e) { } switch(expressionName) { case Index: return 70; case Description: return 230; default: return 150; } }
Source:
<code>protected void generateAPIFiles(ApiImplementor imp) throws IOException { String className = imp.getPrefix().substring(0, 1).toUpperCase() + imp.getPrefix().substring(1); String pkgName = safeName(camelCaseToLowerCaseDash(className)); Path path = getDirectory().resolve(pkgName + "_generated.go"); <START> { END> File file = new File(path.toAbsolutePath().toString()); File dir = file.getParentFile(); if (dir != null && !dir.exists()) { dir.mkdirs(); } if (!file.exists()) { file.createNewFile(); } } System.out.println("Generating " + path.toAbsolutePath()); try (BufferedWriter out = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { out.write(HEADER); out.write(" out.write(" out.write(" out.write("package zap\n\n"); out.write("_imports_"); out.write("type " + className + " struct {\n\tc *Client\n}" + "\n\n" ); for (ApiElement view : imp.getApiViews()) { this.generateGoElement(view, className, imp.getPrefix(), VIEW_ENDPOINT, out); } for (ApiElement action : imp.getApiActions()) { this.generateGoElement(action, className, imp.getPrefix(), ACTION_ENDPOINT, out); } for (ApiElement other : imp.getApiOthers()) { this.generateGoElement(other, className, imp.getPrefix(), OTHER_ENDPOINT, out); } } addImports(path, addImports); addImports = false; }</code><technical_language>This moved a method</technical_language>

Target:
protected void generateAPIFiles(ApiImplementor imp) throws IOException { String className = imp.getPrefix().substring(0, 1).toUpperCase() + imp.getPrefix().substring(1); String pkgName = safeName(camelCaseToLowerCaseDash(className)); Path file = getDirectory().resolve(pkgName + "_generated.go"); createDirAndFile(file); System.out.println("Generating " + file.toAbsolutePath()); try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { out.write(HEADER); out.write(" out.write(" out.write(" out.write("package zap\n\n"); out.write("_imports_"); out.write("type " + className + " struct {\n\tc *Client\n}" + "\n\n"); for (ApiElement view : imp.getApiViews()) { this.generateGoElement(view, className, imp.getPrefix(), VIEW_ENDPOINT, out); } for (ApiElement action : imp.getApiActions()) { this.generateGoElement(action, className, imp.getPrefix(), ACTION_ENDPOINT, out); } for (ApiElement other : imp.getApiOthers()) { this.generateGoElement(other, className, imp.getPrefix(), OTHER_ENDPOINT, out); } } addImports(file, addImports); addImports = false; }
Source:
<code>private void buildDependenciesMap(@NotNull Module module, @NotNull Collection<VirtualFile> erlangModules, @NotNull List<String> globalParseTransforms) { for (VirtualFile erlangModule : erlangModules) { Set<String> dependencies = ContainerUtil.newHashSet(); ErlangFile erlangFile = getErlangFile(erlangModule); addDeclaredDependencies(module, erlangFile, dependencies); <START> dependencies.addAll(resolvePathsFromNames(globalParseTransforms, module)); <END> myPathsToDependenciesMap.put(erlangModule.getPath(), ContainerUtil.newArrayList(dependencies)); } }</code><technical_language>is need resolve paths iteration - need resolved once. Moreover, resolve level above, passing resolved parse transforms this method</technical_language>

Target:
private void buildDependenciesMap(@NotNull Module module, @NotNull Collection<VirtualFile> erlangModules, @NotNull List<String> globalParseTransforms) { for (VirtualFile erlangModule : erlangModules) { Set<String> dependencies = ContainerUtil.newHashSet(); ErlangFile erlangFile = getErlangFile(erlangModule); addDeclaredDependencies(module, erlangFile, dependencies); dependencies.addAll(globalParseTransforms); myPathsToDependenciesMap.put(erlangModule.getPath(), ContainerUtil.newArrayList(dependencies)); } }
Source:
<code>public void testCreate() throws IOException, StripeException { final Customer customer = Customer.retrieve(CUSTOMER_ID); Map<String, Object> params = new HashMap<String, Object>(); params.put("source", "btok_123"); stubRequest( APIResource.RequestMethod.POST, String.format("/v1/customers/%s/sources", customer.getId()), params, Card.class, getResourceAsString("/api_fixtures/card.json") <START> ); <END> final Card card = (Card) customer.getSources().create(params); assertNotNull(card); verifyRequest( APIResource.RequestMethod.POST, String.format("/v1/customers/%s/sources", customer.getId()), params ); }</code><technical_language>getCardFixture</technical_language>

Target:
public void testCreate() throws IOException, StripeException { final Customer customer = Customer.retrieve(CUSTOMER_ID); final Map<String, Object> params = new HashMap<String, Object>(); params.put("source", "btok_123"); stubRequest( APIResource.RequestMethod.POST, String.format("/v1/customers/%s/sources", customer.getId()), params, Card.class, getResourceAsString("/api_fixtures/card.json") ); final Card card = (Card) customer.getSources().create(params); assertNotNull(card); verifyRequest( APIResource.RequestMethod.POST, String.format("/v1/customers/%s/sources", customer.getId()), params ); }
Source:
<code>public boolean createUser() { boolean createdUser = false; <START> if(this.getUserName() !=null && this.getPassword() !=null){ <END> System.out.println("username from CreateuserBean---"+this.getUserName()); System.out.println("password from createuserBean---"+this.getPassword()); } Login user = new Login(userName, password); System.out.println("after the login object set up"); try{ System.out.println("Create user status before calling adduser method"+createdUser); createdUser = loginService.addUser(user); System.out.println("Create user status after calling adduser method"+createdUser); if(createdUser){ FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); session.setAttribute(UserAuthorizationListener.USER_INFO_SESSION_ATTRIBUTE, user); } } catch (UserLoginException e) { e.printStackTrace(); } return createdUser; }</code><technical_language>Remove statements, output user/password</technical_language>

Target:
public boolean createUser() { boolean createdUser = false; if (this.getUserName() != null && this.getPassword() != null) { } Login user = new Login(userName, password); try { createdUser = loginService.addUser(user); if (createdUser) { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); session.setAttribute(UserAuthorizationListener.USER_INFO_SESSION_ATTRIBUTE, user); } } catch (UserLoginException e) { log.error("Error in create user" + e.getMessage()); } return createdUser; }
Source:
<code>public void testOnContainerCompleted() throws Exception { new Context() {{ final List<CompletableFuture<Void>> addContainerRequestFutures = new ArrayList<>(); addContainerRequestFutures.add(new CompletableFuture<>()); addContainerRequestFutures.add(new CompletableFuture<>()); final AtomicInteger addContainerRequestFuturesNumCompleted = new AtomicInteger(0); final CompletableFuture<Void> removeContainerRequestFuture = new CompletableFuture<>(); final CompletableFuture<Void> startContainerAsyncFuture = new CompletableFuture<>(); testingYarnAMRMClientAsyncBuilder.setGetMatchingRequestsFunction(ignored -> Collections.singletonList(Collections.singletonList(YarnResourceManagerDriver.getContainerRequest(testingResource)))); testingYarnAMRMClientAsyncBuilder.setAddContainerRequestConsumer((ignored1, ignored2) -> addContainerRequestFutures.get(addContainerRequestFuturesNumCompleted.getAndIncrement()).complete(null)); testingYarnAMRMClientAsyncBuilder.setRemoveContainerRequestConsumer((ignored1, ignored2) -> removeContainerRequestFuture.complete(null)); testingYarnNMClientAsyncBuilder.setStartContainerAsyncConsumer((ignored1, ignored2, ignored3) -> startContainerAsyncFuture.complete(null)); resourceEventHandlerBuilder.setOnWorkerTerminatedConsumer((ignore1, ignore2) -> getDriver().requestResource(testingTaskExecutorProcessSpec)); runTest(() -> { <START> getDriver().requestResource(testingTaskExecutorProcessSpec); <END> ((YarnResourceManagerDriver) getDriver()).getYarnContainerEventHandler().onContainersAllocated(ImmutableList.of(testingContainer)); verifyFutureCompleted(addContainerRequestFutures.get(0)); verifyFutureCompleted(removeContainerRequestFuture); verifyFutureCompleted(startContainerAsyncFuture); ContainerStatus testingContainerStatus = createTestingContainerStatus(testingContainer.getId()); ((YarnResourceManagerDriver) getDriver()).getYarnContainerEventHandler().onContainersCompleted(ImmutableList.of(testingContainerStatus)); verifyFutureCompleted(addContainerRequestFutures.get(1)); }); }}; }</code><technical_language>This interface invoked main thread</technical_language>

Target:
public void testOnContainerCompleted() throws Exception { new Context() {{ addContainerRequestFutures.add(new CompletableFuture<>()); addContainerRequestFutures.add(new CompletableFuture<>()); testingYarnAMRMClientAsyncBuilder.setAddContainerRequestConsumer((ignored1, ignored2) -> addContainerRequestFutures.get(addContainerRequestFuturesNumCompleted.getAndIncrement()).complete(null)); resourceEventHandlerBuilder.setOnWorkerTerminatedConsumer((ignore1, ignore2) -> getDriver().requestResource(testingTaskExecutorProcessSpec)); runTest(() -> { runInMainThread(() -> getDriver().requestResource(testingTaskExecutorProcessSpec)); resourceManagerClientCallbackHandler.onContainersAllocated(ImmutableList.of(testingContainer)); ContainerStatus testingContainerStatus = createTestingContainerCompletedStatus(testingContainer.getId()); resourceManagerClientCallbackHandler.onContainersCompleted(ImmutableList.of(testingContainerStatus)); verifyFutureCompleted(addContainerRequestFutures.get(1)); }); }}; }
Source:
<code>public Object invoke(MethodInvocation methodInvocation) throws Throwable { Object result; try { result = methodInvocation.proceed(); } catch (ValidationException e) { List<ErrorMessage> messages = Lists.newArrayList(); for (Error error : e.errors) { messages.add(new ErrorMessage(error.message)); } return Reply.with(new Errors(messages)).status(SC_BAD_REQUEST).as(Json.class); } catch (ClassCastException e) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(defaultInternalServerError)))).status(SC_BAD_REQUEST).as(Json.class); } catch (NotFoundException e) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(e.getMessage())))).status(SC_NOT_FOUND).as(Json.class); <START> } catch (OperatorException e) { <END> return Reply.with(new Errors(Lists.<ErrorMessage>newArrayList(new ErrorMessage(e.getMessage())))).status(SC_CONFLICT); } catch (RuntimeException e) { logger.error("Exception stack trace", e); if(isNullOrEmpty(e.getMessage())) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(defaultInternalServerError)))).error().as(Json.class); } return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(e.getMessage())))).error().as(Json.class); } if (!(result instanceof Reply)) { throw new ProgrammerMistake("Wrong interceptor binding was performed. It seems that methods that are not returning" + " Reply objects are matched."); } return result; }</code><technical_language>I need add another catch clause here... OperatorException is a RuntimeException clause for it. status code is returned Status code (409) indicating request completed due a conflict current state of resource. - I current situation is "conflict current state". do</technical_language>

Target:
public Object invoke(MethodInvocation methodInvocation) throws Throwable { Object result; try { result = methodInvocation.proceed(); } catch (ValidationException e) { List<ErrorMessage> messages = Lists.newArrayList(); for (Error error : e.errors) { messages.add(new ErrorMessage(error.message)); } return Reply.with(new Errors(messages)).status(SC_BAD_REQUEST).as(Json.class); } catch (ClassCastException e) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(defaultInternalServerError)))).status(SC_BAD_REQUEST).as(Json.class); } catch (NotFoundException e) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(e.getMessage())))).status(SC_NOT_FOUND).as(Json.class); } catch (RuntimeException e) { logger.error("Exception stack trace", e); if(isNullOrEmpty(e.getMessage())) { return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(defaultInternalServerError)))).error().as(Json.class); } return Reply.with(new Errors(Lists.newArrayList(new ErrorMessage(e.getMessage())))).error().as(Json.class); } if (!(result instanceof Reply)) { throw new ProgrammerMistake("Wrong interceptor binding was performed. It seems that methods that are not returning" + " Reply objects are matched."); } return result; }
Source:
<code>public JFXSearchPanel() { super(); init(); setPrefWidth(350d); setMinWidth(350d); <START> setMaxWidth(500d); <END> }</code><technical_language>This change benefit field bigger. PREF size MAX size</technical_language>

Target:
public JFXSearchPanel() { super(); init(); setPrefWidth(350d); setMinWidth(350d); setMaxWidth(350d); }
Source:
<code>public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { try { <START> Object parameter = getItemsSource().get(position); <END> if (onLongClick != null && onLongClick.canExecute(parameter)) { onLongClick.execute(parameter); return true; } } catch (Exception e) { } return false; }</code><technical_language>this moved in delegate</technical_language>

Target:
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { try { Object parameter = getItemsSource().get(position); if (!mDelegate.isDisposed() && mDelegate.getLongClick().canExecute(parameter)) { mDelegate.getLongClick().execute(parameter); return true; } } catch (Exception e) { } return false; }
Source:
<code><START> public InnerBuilder setCepSinkType(final CepSinkType cepSinkType) { <END> if (this.cepSinkType != null) { throw new IllegalStateException("Sink type cannot be defined twice!"); } this.cepSinkType = cepSinkType; return this; }</code><technical_language>CepInput, do InnerBuilder methods public</technical_language>

Target:
private InnerBuilder setCepSinkType(final CepSinkType cepSinkType) { if (this.cepSinkType != null) { throw new IllegalStateException("Sink type cannot be defined twice!"); } this.cepSinkType = cepSinkType; return this; }
Source:
<code>public void plotGraph(StaplerRequest req, StaplerResponse rsp) throws IOException { if (ChartUtil.awtProblemCause != null) { rsp.sendRedirect2(req.getContextPath() + "/images/headless.png"); return; } setWidth(req); setHeight(req); setNumBuilds(req); setRightBuildNum(req); setHasLegend(req); setTitle(req); setStyle(req); setUseDescr(req); <START> setDescription(req); <END> generatePlot(true); ChartUtil.generateGraph(req, rsp, plot, getWidth(), getHeight()); }</code><technical_language>This remove description set, please remove</technical_language>

Target:
public void plotGraph(StaplerRequest req, StaplerResponse rsp) throws IOException { if (ChartUtil.awtProblemCause != null) { rsp.sendRedirect2(req.getContextPath() + "/images/headless.png"); return; } setWidth(req); setHeight(req); setNumBuilds(req); setRightBuildNum(req); setHasLegend(req); setTitle(req); setStyle(req); setUseDescr(req); generatePlot(true); ChartUtil.generateGraph(req, rsp, plot, getWidth(), getHeight()); }
Source:
<code>public void stop(BundleContext context) throws Exception { <START> channelTypeServiceBinder.close(); <END> thingTypeServiceBinder.close(); Activator.context = null; }</code><technical_language>set fields null here</technical_language>

Target:
public void stop(BundleContext context) throws Exception { channelTypeServiceBinder.close(); thingTypeServiceBinder.close(); channelTypeServiceBinder = null; thingTypeServiceBinder = null; Activator.context = null; }
Source:
<code>public DateTime (Composite parent, int style) { super (parent, checkStyle (style)); if ((this.style & SWT.CALENDAR) == 0) { <START> createText((this.style & SWT.DROP_DOWN) != 0); <END> } initAccessible (); }</code><technical_language>retain else condition is in original code. This sets hilighting of today's date in calendar</technical_language>

Target:
public DateTime (Composite parent, int style) { super (parent, checkStyle (style)); if (isDate() || isTime()) { createText(); } if (isDateWithDropDownButton()) { createDropDownButton(); createPopupShell(-1, -1, -1); addListener(SWT.Resize, new Listener() { public void handleEvent(Event event) { setDropDownButtonSize(); } }); } initAccessible (); if (isDateWithDropDownButton()) { Point size = computeSize(SWT.DEFAULT, SWT.DEFAULT); setBounds(0, 0, size.x, size.y); } }
Source:
<code>public static IndicesAliases parse(Map<String, Object> resp) { final Map<String, Map<String, Alias> > indices = new HashMap<String, Map<String, Alias> > (); for (Map.Entry<String, Object> index : resp.entrySet()) { final Map<String, Object> metadata = (Map<String, Object>) index.getValue(); final Map<String, Object> aliases = (Map<String, Object>) metadata.get("aliases"); final Map<String, Alias> indexAliases = new HashMap<String, Alias> (); indices.put(index.getKey(), indexAliases); for (Map.Entry<String, Object> entry : aliases.entrySet()) { String name = entry.getKey(); String searchRouting = null; String indexRouting = null; Map<String, Object> filter = null; if (metadata.containsKey("search_routing")) { searchRouting = (String) metadata.get("search_routing"); } if (metadata.containsKey("index_routing")) { indexRouting = (String) metadata.get("index_routing"); } if (metadata.containsKey("filter")) { filter = (Map<String, Object>) metadata.get("filter"); <START> } <END> Alias alias = new Alias(name, searchRouting, indexRouting, filter); indexAliases.put(alias.name, alias); } } return new IndicesAliases(Collections.unmodifiableMap(indices)); }</code><technical_language>((Map<String, Object>)value).containsKey("...")? metadata map is named aliases</technical_language>

Target:
public static IndicesAliases parse(Map<String, Object> resp) { final Map<String, Map<String, Alias> > indices = new HashMap<String, Map<String, Alias> > (); for (Map.Entry<String, Object> index : resp.entrySet()) { final Map<String, Object> metadata = (Map<String, Object>) index.getValue(); final Map<String, Map<String, Object> > aliases = (Map<String, Map<String, Object> >) metadata.get("aliases"); final Map<String, Alias> indexAliases = new HashMap<String, Alias> (); indices.put(index.getKey(), indexAliases); for (Map.Entry<String, Map<String, Object> > entry : aliases.entrySet()) { String name = entry.getKey(); Map<String, Object> aliasMetadata = entry.getValue(); String searchRouting = null; String indexRouting = null; Map<String, Object> filter = null; if (aliasMetadata.containsKey("search_routing")) { searchRouting = (String) aliasMetadata.get("search_routing"); } if (aliasMetadata.containsKey("index_routing")) { indexRouting = (String) aliasMetadata.get("index_routing"); } if (aliasMetadata.containsKey("filter")) { filter = (Map<String, Object>) aliasMetadata.get("filter"); } Alias alias = new Alias(name, searchRouting, indexRouting, filter); indexAliases.put(alias.name, alias); } } return new IndicesAliases(Collections.unmodifiableMap(indices)); }
Source:
<code>static <T> java.util.List<T> asJava(IndexedSeq<T> seq) { <START> return new SeqAsJavaList<T>(seq) { <END> private static final long serialVersionUID = 1L; @Override public java.util.ListIterator<T> listIterator() { return JavaConverters.listIterator(((IndexedSeq<T>) delegate), 0); } @Override public java.util.ListIterator<T> listIterator(int index) { return JavaConverters.listIterator(((IndexedSeq<T>) delegate), index); } }; }</code><technical_language>Lets pass ListIterator constructor method reference do subclass it: java return new SeqAsJavaList<T>(seq, (delegate, index) -> new IndexedSeqListIterator<>((IndexedSeq<T>) delegate, index));</technical_language>

Target:
static <T> java.util.List<T> asJava(IndexedSeq<T> seq) { return new SeqAsJavaList<>(seq, IndexedSeqListIterator::new); }
Source:
<code>public static void main(String[] args) throws Exception { if(args.length < 2) { usage(); return; } try (FileInputStream argIS = new FileInputStream(args[0]); BufferedReader modelReader = new BufferedReader(new FileReader(args[1]))) { String chartTitle = modelReader.readLine(); List<String> listCategories = new ArrayList<String>(3); List<Double> listValues = new ArrayList<Double>(3); String ln; while((ln = modelReader.readLine()) != null){ String[] vals = ln.split("\\s+"); listCategories.add(vals[0]); listValues.add(Double.valueOf(vals[1])); } String[] categories = listCategories.toArray(new String[listCategories.size()]); Double[] values = listValues.toArray(new Double[listValues.size()]); try (XWPFDocument doc = new XWPFDocument(argIS)) { XWPFChart chart = findChart(doc); setBarData(chart, chartTitle, categories, values); <START> setColumnData(chart, "Column variant"); <END> try (OutputStream out = new FileOutputStream("bar-chart-demo-output.docx")) { doc.write(out); } } } System.out.println("Done"); }</code><technical_language>In original example, charts created a template of them. of populated setBarData while other populated setColumnData. In example, start a template charts change one, applying methods... I suggest experiment more of new API changes approach</technical_language>

Target:
public static void main(String[] args) throws Exception { if(args.length < 2) { usage(); return; } try (FileInputStream argIS = new FileInputStream(args[0]); BufferedReader modelReader = new BufferedReader(new FileReader(args[1]))) { String chartTitle = modelReader.readLine(); List<String> listCategories = new ArrayList<String>(3); List<Double> listValues = new ArrayList<Double>(3); String ln; while((ln = modelReader.readLine()) != null){ String[] vals = ln.split("\\s+"); listCategories.add(vals[0]); listValues.add(Double.valueOf(vals[1])); } String[] categories = listCategories.toArray(new String[listCategories.size()]); Double[] values = listValues.toArray(new Double[listValues.size()]); try (XWPFDocument doc = new XWPFDocument(argIS)) { XWPFChart chart = doc.getCharts().get(0); setBarData(chart, chartTitle, categories, values); chart = doc.getCharts().get(1); setColumnData(chart, "Column variant"); try (OutputStream out = new FileOutputStream("bar-chart-demo-output.docx")) { doc.write(out); } } } System.out.println("Done"); }
Source:
<code>public @NonNull List<ITmfStateInterval> getStatusIntervalsForThread(int threadQuark, long start, long end, long resolution, IProgressMonitor monitor) { <START> ITmfStateSystem ssq = getStateSystem(); <END> if (ssq == null) { @SuppressWarnings("null") @NonNull List<ITmfStateInterval> empty = Collections.EMPTY_LIST; return empty; } try { int statusQuark = ssq.getQuarkRelative(threadQuark, Attributes.STATUS); List<ITmfStateInterval> statusIntervals = StateSystemUtils.queryHistoryRange(ssq, statusQuark, Math.max(start, ssq.getStartTime()), Math.min(end - 1, ssq.getCurrentEndTime()), resolution, monitor); return statusIntervals; } catch (AttributeNotFoundException | StateSystemDisposedException e) { } @SuppressWarnings("null") @NonNull List<ITmfStateInterval> empty = Collections.EMPTY_LIST; return empty; }</code><technical_language>ssq -> ss</technical_language>

Target:
public @NonNull List<ITmfStateInterval> getStatusIntervalsForThread(int threadQuark, long start, long end, long resolution, IProgressMonitor monitor) { ITmfStateSystem ss = getStateSystem(); if (ss == null) { @SuppressWarnings("null") @NonNull List<ITmfStateInterval> empty = Collections.EMPTY_LIST; return empty; } try { int statusQuark = ss.getQuarkRelative(threadQuark, Attributes.STATUS); List<ITmfStateInterval> statusIntervals = StateSystemUtils.queryHistoryRange(ss, statusQuark, Math.max(start, ss.getStartTime()), Math.min(end - 1, ss.getCurrentEndTime()), resolution, monitor); return statusIntervals; } catch (AttributeNotFoundException | StateSystemDisposedException e) { } @SuppressWarnings("null") @NonNull List<ITmfStateInterval> empty = Collections.EMPTY_LIST; return empty; }
Source:
<code><START> void populateCommits(SRunningBuild sRunningBuild) { <END> List<SVcsModification> changes = sRunningBuild.getContainingChanges(); if (changes == null) { return; } for (SVcsModification change : changes) { Collection<SUser> committers = change.getCommitters(); String slackUserName = null; if (committers != null && !committers.isEmpty()) { SUser committer = committers.iterator().next(); slackUserName = committer.getPropertyValue(SlackNotificator.USERNAME_KEY); Loggers.ACTIVITIES.debug("Resolved committer " + change.getUserName() + " to Slack User " + slackUserName); } commits.add(new Commit(change.getVersion(), change.getDescription(), change.getUserName(), slackUserName)); } }</code><technical_language>this method public real this class does. (which is good)</technical_language>

Target:
public void populateCommits(SRunningBuild sRunningBuild) { List<SVcsModification> changes = sRunningBuild.getContainingChanges(); if (changes == null) { return; } for (SVcsModification change : changes) { Collection<SUser> committers = change.getCommitters(); String slackUserName = null; if (committers != null && !committers.isEmpty()) { SUser committer = committers.iterator().next(); slackUserName = committer.getPropertyValue(SlackNotificator.USERNAME_KEY); Loggers.ACTIVITIES.debug("Resolved committer " + change.getUserName() + " to Slack User " + slackUserName); } commits.add(new Commit(change.getVersion(), change.getDescription(), change.getUserName(), slackUserName)); } }
Source:
<code>protected void onInit() { Properties properties = new Properties(); properties.put("locators", "localhost[7777]"); <START> properties.put("log-level", "warning"); <END> this.cache = new CacheFactory(properties).create(); super.onInit(); }</code><technical_language>I add mcast-port=0 a default</technical_language>

Target:
protected void onInit() { Properties properties = new Properties(); properties.put("locators", "localhost[7777]"); properties.put("log-level", "warning"); properties.put("mcast-port", "0"); this.cache = new CacheFactory(properties).create(); super.onInit(); }
Source:
<code>protected static int[] toIntPortArray(Object v) { <START> Collection<String> inboundPortEntries = toListOfStrings(v); <END> PortRange portRange = PortRanges.fromCollection(inboundPortEntries); int[] portArray = ArrayUtils.toPrimitive(Iterables.toArray(portRange, Integer.class)); return portArray; }</code><technical_language>fully compatible. toIntArray supports format [1,2,3]. accepts int arrays if passed Java code. supported, hard opinion one. nice a test for new method. useful</technical_language>

Target:
static int[] toIntPortArray(Object v) { PortRange portRange = PortRanges.fromIterable(Collections.singletonList(v)); int[] portArray = ArrayUtils.toPrimitive(Iterables.toArray(portRange, Integer.class)); return portArray; }
Source:
<code>public TestContainer[] create(ExamSystem system) { if (system.getOptions(CarbonDistributionBaseOption.class).length > 1) { logger.warn("Multiple distribution options are specified in the configuration!!!"); } <START> List<TestContainer> containers = Arrays.asList(system.getOptions(CarbonDistributionBaseOption.class)).stream() <END> .map(option -> new CarbonTestContainer(system, option)).collect(Collectors.toList()); if (containers.isEmpty()) { containers.add(new CarbonTestContainer(system, getDefaultConfiguration())); } return containers.toArray(new TestContainer[containers.size()]); }</code><technical_language>streams, usual is operation in a new line. is more readable</technical_language>

Target:
public TestContainer[] create(ExamSystem system) { if (system.getOptions(CarbonDistributionBaseOption.class).length > 1) { logger.warn("Multiple distribution options are specified in the configuration!!!"); } List<TestContainer> containers = Arrays.stream(system.getOptions(CarbonDistributionBaseOption.class)) .map(option -> new CarbonTestContainer(system, option)) .collect(Collectors.toList()); if (containers.isEmpty()) { containers.add(new CarbonTestContainer(system, getDefaultConfiguration())); } return containers.toArray(new TestContainer[containers.size()]); }