auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void process(CommandLine cl, @SuppressWarnings("rawtypes") Map stormConf) throws Exception { String appName = cl.getOptionValue("appname", "Storm-on-Yarn"); String queue = cl.getOptionValue("queue", "default"); String storm_zip_location = cl.getOptionValue("stormZip"); Integer amSize = (Integer) stormConf.get(Config.MASTER_SIZE_MB); StormOnYarn storm = null; try { storm = StormOnYarn.launchApplication(appName, queue, amSize, stormConf, storm_zip_location); LOG.debug("Submitted application's ID:" + storm.getAppId()); String storm_yaml_output = cl.getOptionValue("stormConfOutput"); if (storm_yaml_output!=null && storm_yaml_output.length()>0) { StormMaster.Client client = storm.getClient(); if (client != null) StormMasterCommand.downloadStormYaml(client, storm_yaml_output); else <START> LOG.warn("No storm.yaml is downaloaded"); <END> } String output = cl.getOptionValue("output"); if (output == null) System.out.println(storm.getAppId()); else { PrintStream os = new PrintStream(output); os.println(storm.getAppId()); os.flush(); os.close(); } } finally { if (storm != null) { storm.stop(); } } }</code><technical_language>another minor typo s/downaloaded/downloaded/</technical_language>

Target:
public void process(CommandLine cl, @SuppressWarnings("rawtypes") Map stormConf) throws Exception { String appName = cl.getOptionValue("appname", "Storm-on-Yarn"); String queue = cl.getOptionValue("queue", "default"); String storm_zip_location = cl.getOptionValue("stormZip"); Integer amSize = (Integer) stormConf.get(Config.MASTER_SIZE_MB); StormOnYarn storm = null; try { storm = StormOnYarn.launchApplication(appName, queue, amSize, stormConf, storm_zip_location); LOG.debug("Submitted application's ID:" + storm.getAppId()); String storm_yaml_output = cl.getOptionValue("stormConfOutput"); if (storm_yaml_output!=null && storm_yaml_output.length()>0) { StormMaster.Client client = storm.getClient(); if (client != null) StormMasterCommand.downloadStormYaml(client, storm_yaml_output); else LOG.warn("No storm.yaml is downloaded"); } String output = cl.getOptionValue("output"); if (output == null) System.out.println(storm.getAppId()); else { PrintStream os = new PrintStream(output); os.println(storm.getAppId()); os.flush(); os.close(); } } finally { if (storm != null) { storm.stop(); } } }
Source:
<code>private <T extends WrappedModule<?, ?>> @Nullable String setModuleHandlers(String rUID, List<T> modules) { StringBuffer sb = null; for (T mm : modules) { final Module m = mm.unwrap(); try { ModuleHandler moduleHandler = getModuleHandler(m, rUID); if (moduleHandler != null) { if (mm instanceof WrappedAction) { ((WrappedAction) mm).setModuleHandler((ActionHandler) moduleHandler); } else if (mm instanceof WrappedCondition) { ((WrappedCondition) mm).setModuleHandler((ConditionHandler) moduleHandler); } else if (mm instanceof WrappedTrigger) { ((WrappedTrigger) mm).setModuleHandler((TriggerHandler) moduleHandler); } } else { if (sb == null) { <START> sb = new StringBuffer(); <END> } String message = "Missing handler '" + m.getTypeUID() + "' for module '" + m.getId() + "'"; sb.append(message).append("\n"); logger.trace(message); } } catch (Throwable t) { if (sb == null) { sb = new StringBuffer(); } String message = "Getting handler '" + m.getTypeUID() + "' for module '" + m.getId() + "' failed: " + t.getMessage(); sb.append(message).append("\n"); logger.trace(message); } } return sb != null ? sb.toString() : null; }</code><technical_language>I guess StringBuilder is preferred StringBuilder</technical_language>

Target:
private <T extends WrappedModule<?, ?>> @Nullable String setModuleHandlers(String rUID, List<T> modules) { StringBuilder sb = null; for (T mm : modules) { final Module m = mm.unwrap(); try { ModuleHandler moduleHandler = getModuleHandler(m, rUID); if (moduleHandler != null) { if (mm instanceof WrappedAction) { ((WrappedAction) mm).setModuleHandler((ActionHandler) moduleHandler); } else if (mm instanceof WrappedCondition) { ((WrappedCondition) mm).setModuleHandler((ConditionHandler) moduleHandler); } else if (mm instanceof WrappedTrigger) { ((WrappedTrigger) mm).setModuleHandler((TriggerHandler) moduleHandler); } } else { if (sb == null) { sb = new StringBuilder(); } String message = "Missing handler '" + m.getTypeUID() + "' for module '" + m.getId() + "'"; sb.append(message).append("\n"); logger.trace(message); } } catch (Throwable t) { if (sb == null) { sb = new StringBuilder(); } String message = "Getting handler '" + m.getTypeUID() + "' for module '" + m.getId() + "' failed: " + t.getMessage(); sb.append(message).append("\n"); logger.trace(message); } } return sb != null ? sb.toString() : null; }
Source:
<code>public void setSelected(final String modelName) { for (int i = 0; i < listBox.getItemCount(); i++) { <START> if (listBox.getItemText(i).equals(modelName)) { <END> listBox.setSelectedIndex(i); return; } } }</code><technical_language>please Objects.equals</technical_language>

Target:
public void setSelected(final String modelName) { for (int i = 0; i < listBox.getItemCount(); i++) { if (Objects.equals(listBox.getItemText(i), modelName)) { listBox.setSelectedIndex(i); return; } } }
Source:
<code>public void registerUserNotUsernamePasswordPolicy() { <START> adminClient.realm("test").update(RealmBuilder.create() <END> .passwordPolicy(NotUsernamePasswordPolicyProviderFactory.ID).build()); loginPage.open(); assertTrue(loginPage.isCurrent()); loginPage.clickRegister(); registerPage.assertCurrent(); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", "registerUserNotUsername", "registerUserNotUsername", "registerUserNotUsername"); assertTrue(registerPage.isCurrent()); assertEquals("Invalid password: must not be equal to the username.", registerPage.getError()); adminClient.realm("test").users().create(UserBuilder.create().username("registerUserNotUsername").build()); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", "registerUserNotUsername", "registerUserNotUsername", "registerUserNotUsername"); assertTrue(registerPage.isCurrent()); assertEquals("Username already exists.", registerPage.getError()); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", null, "password", "password"); assertTrue(registerPage.isCurrent()); assertEquals("Please specify username.", registerPage.getError()); }</code><technical_language>Please remove this. Tests intent a string a constant here</technical_language>

Target:
public void registerUserNotUsernamePasswordPolicy() { adminClient.realm("test").update(RealmBuilder.create().passwordPolicy("notUsername").build()); loginPage.open(); assertTrue(loginPage.isCurrent()); loginPage.clickRegister(); registerPage.assertCurrent(); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", "registerUserNotUsername", "registerUserNotUsername", "registerUserNotUsername"); assertTrue(registerPage.isCurrent()); assertEquals("Invalid password: must not be equal to the username.", registerPage.getError()); adminClient.realm("test").users().create(UserBuilder.create().username("registerUserNotUsername").build()); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", "registerUserNotUsername", "registerUserNotUsername", "registerUserNotUsername"); assertTrue(registerPage.isCurrent()); assertEquals("Username already exists.", registerPage.getError()); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", null, "password", "password"); assertTrue(registerPage.isCurrent()); assertEquals("Please specify username.", registerPage.getError()); }
Source:
<code>public void run() { try { WatchService watchService = KeyStoreWatcher.this.watchService; <START> while (watchService != null) { <END> WatchKey key = watchService.take(); Path watchedPath = (Path) key.watchable(); Map<String, List<Store>> pathRegistration = watchedPaths.get(watchedPath); Set<Store> toNotify = new HashSet<Store>(); if (pathRegistration != null) { for (WatchEvent<?> event : key.pollEvents()) { if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) { Path context = (Path) event.context(); String name = context.getFileName().toString(); System.out.println("File Name " + name); List<Store> stores = pathRegistration.get(name); if (stores != null) { for (Store current : stores) { toNotify.add(current); } } } else if (StandardWatchEventKinds.OVERFLOW.equals(event.kind())) { for (List<Store> stores : pathRegistration.values()) { for (Store current : stores) { toNotify.add(current); } } } } } key.reset(); for (Store current : toNotify) { current.modified(); } } } catch (ClosedWatchServiceException | InterruptedException e) { } }</code><technical_language>This condition true false; watchService local variable needs updated bottom of loop</technical_language>

Target:
public void run() { try { WatchService watchService = null; while ((watchService = KeyStoreWatcher.this.watchService) != null) { WatchKey key = watchService.take(); Path watchedPath = (Path) key.watchable(); Set<Store> toNotify = new HashSet<Store>(); synchronized (watchedPaths) { Map<String, List<Store>> pathRegistration = watchedPaths.get(watchedPath); if (pathRegistration != null) { for (WatchEvent<?> event : key.pollEvents()) { if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) { Path context = (Path) event.context(); String name = context.getFileName().toString(); List<Store> stores = pathRegistration.get(name); if (stores != null) { for (Store current : stores) { toNotify.add(current); } } } else if (StandardWatchEventKinds.OVERFLOW.equals(event.kind())) { for (List<Store> stores : pathRegistration.values()) { for (Store current : stores) { toNotify.add(current); } } } } } key.reset(); } for (Store current : toNotify) { current.modified(); } } } catch (ClosedWatchServiceException | InterruptedException e) { } }
Source:
<code>public static ByteBuffer[] encodeValues( Object[] values, List<DataType> fieldTypes, CodecRegistry codecRegistry, ProtocolVersion protocolVersion) { Preconditions.checkArgument( values.length <= fieldTypes.size(), "Too many values (expected %s, got %s)", fieldTypes.size(), values.length); ByteBuffer[] encodedValues = new ByteBuffer[fieldTypes.size()]; for (int i = 0; i < values.length; i++) { Object value = values[i]; ByteBuffer encodedValue; if (value == null) { encodedValue = null; <START> } else if (value instanceof Token) { <END> if (value instanceof Murmur3Token) { encodedValue = TypeCodecs.BIGINT.encode(((Murmur3Token) value).getValue(), protocolVersion); } else if (value instanceof ByteOrderedToken) { encodedValue = TypeCodecs.BLOB.encode(((ByteOrderedToken) value).getValue(), protocolVersion); } else if (value instanceof RandomToken) { encodedValue = TypeCodecs.VARINT.encode(((RandomToken) value).getValue(), protocolVersion); } else { throw new IllegalArgumentException("Unsupported token type " + value.getClass()); } } else { TypeCodec<Object> codec = codecRegistry.codecFor(fieldTypes.get(i), value); encodedValue = codec.encode(value, protocolVersion); } encodedValues[i] = encodedValue; } return encodedValues; }</code><technical_language>This works of built-in codecs encode null a CQL null. in theory plug codec registry, default codecs handle null differently. out of principle I prefer letting codec handle it. suggested JIRA ticket, changing line 64 to: java TypeCodec<Object> codec = (value == null) ? codecRegistry.codecFor(fieldTypes.get(i)) : codecRegistry.codecFor(fieldTypes.get(i), value); encodedValue = codec.encode(value, protocolVersion);</technical_language>

Target:
public static ByteBuffer[] encodeValues( Object[] values, List<DataType> fieldTypes, CodecRegistry codecRegistry, ProtocolVersion protocolVersion) { Preconditions.checkArgument( values.length <= fieldTypes.size(), "Too many values (expected %s, got %s)", fieldTypes.size(), values.length); ByteBuffer[] encodedValues = new ByteBuffer[fieldTypes.size()]; for (int i = 0; i < values.length; i++) { Object value = values[i]; ByteBuffer encodedValue; if (value instanceof Token) { if (value instanceof Murmur3Token) { encodedValue = TypeCodecs.BIGINT.encode(((Murmur3Token) value).getValue(), protocolVersion); } else if (value instanceof ByteOrderedToken) { encodedValue = TypeCodecs.BLOB.encode(((ByteOrderedToken) value).getValue(), protocolVersion); } else if (value instanceof RandomToken) { encodedValue = TypeCodecs.VARINT.encode(((RandomToken) value).getValue(), protocolVersion); } else { throw new IllegalArgumentException("Unsupported token type " + value.getClass()); } } else { TypeCodec<Object> codec = (value == null) ? codecRegistry.codecFor(fieldTypes.get(i)) : codecRegistry.codecFor(fieldTypes.get(i), value); encodedValue = codec.encode(value, protocolVersion); } encodedValues[i] = encodedValue; } return encodedValues; }
Source:
<code>public void resetCommitMessageComponent() { <START> overwrittenCommitMessage = commitMessageComponent.getCommitMessage(); <END> loadInitialState(new CommitHelper(currentRepository)); }</code><technical_language>I turn "" pure whitespace null</technical_language>

Target:
public void resetCommitMessageComponent() { if (currentRepository != null) { String commitMessage = commitMessageComponent.getCommitMessage(); if (commitMessage.trim().length() > 0) { CommitMessageHistory.saveCommitHistory(commitMessage); } loadInitialState(new CommitHelper(currentRepository)); } }
Source:
<code>protected void processChecks(final UserSelection userSelection, final ImportGermplasmListForm form) { final String[] selectedCheck = form.getSelectedCheck(); if (selectedCheck != null && selectedCheck.length != 0) { ImportedGermplasmMainInfo importedGermplasmMainInfoToUse = userSelection.getImportedCheckGermplasmMainInfo(); if (importedGermplasmMainInfoToUse == null) { importedGermplasmMainInfoToUse = userSelection.getImportedGermplasmMainInfo(); } if (importedGermplasmMainInfoToUse != null) { for (int i = 0; i < selectedCheck.length; i++) { if (NumberUtils.isNumber(selectedCheck[i])) { importedGermplasmMainInfoToUse.getImportedGermplasmList().getImportedGermplasms().get(i).setEntryTypeValue(selectedCheck[i]); importedGermplasmMainInfoToUse.getImportedGermplasmList().getImportedGermplasms().get(i) .setEntryTypeCategoricalID(Integer.parseInt(selectedCheck[i])); } } } <START> } <END> }</code><technical_language>done testing checks. This some special handling for checks preserved</technical_language>

Target:
protected void processChecks(final UserSelection userSelection, final ImportGermplasmListForm form) { final String[] selectedCheck = form.getSelectedCheck(); if (selectedCheck != null && selectedCheck.length != 0) { ImportedGermplasmMainInfo importedGermplasmMainInfoToUse = userSelection.getImportedCheckGermplasmMainInfo(); if (importedGermplasmMainInfoToUse == null) { importedGermplasmMainInfoToUse = userSelection.getImportedGermplasmMainInfo(); } if (importedGermplasmMainInfoToUse != null) { for (int i = 0; i < selectedCheck.length; i++) { if (NumberUtils.isNumber(selectedCheck[i])) { importedGermplasmMainInfoToUse.getImportedGermplasmList().getImportedGermplasms().get(i) .setEntryTypeValue(selectedCheck[i]); importedGermplasmMainInfoToUse.getImportedGermplasmList().getImportedGermplasms().get(i) .setEntryTypeCategoricalID(Integer.parseInt(selectedCheck[i])); } } } } else { if (userSelection.getImportedGermplasmMainInfo() != null && userSelection.getImportedGermplasmMainInfo().getImportedGermplasmList() != null && userSelection.getImportedGermplasmMainInfo().getImportedGermplasmList().getImportedGermplasms() != null) { for (final ImportedGermplasm germplasm : userSelection.getImportedGermplasmMainInfo().getImportedGermplasmList() .getImportedGermplasms()) { germplasm.setEntryTypeCategoricalID(null); germplasm.setEntryTypeValue(""); } } } }
Source:
<code>public void start() throws Exception { if (started.compareAndSet(false, true)) { node.start(); <START> started.set(true); <END> } }</code><technical_language>need this compareAndSet set true</technical_language>

Target:
public void start() throws Exception { if (running.compareAndSet(false, true)) { node.start(); } }
Source:
<code>public PoolDto createPool(@RequestBody PoolDto pool, UriComponentsBuilder uriBuilder, HttpServletResponse response) throws IOException { Long id = poolService.savePool(Dtos.to(pool)); <START> UriComponents uriComponents = uriBuilder.path("/{id}").buildAndExpand(id); <END> response.setHeader("Location", uriComponents.toUri().toString()); return getPoolById(id); }</code><technical_language>"/pool/{id}"</technical_language>

Target:
public PoolDto createPool(@RequestBody PoolDto pool, UriComponentsBuilder uriBuilder, HttpServletResponse response) throws IOException { Long id = poolService.savePool(Dtos.to(pool)); return getPoolById(id); }
Source:
<code>public User getUser(Integer userId) throws APIException { <START> User user = dao.getUser(userId); <END> if (isDaemon(user)) { log.warn("requested User of Id '" + userId + "' is Daemon"); return null; } return user; }</code><technical_language>This changed, changing search methods</technical_language>

Target:
public User getUser(Integer userId) throws APIException { return dao.getUser(userId); }
Source:
<code>private Object parseId(Map message) throws JsonRpcException { if (!message.containsKey("id")) { <START> throw new JsonRpcException(null, invalid("required key `id` missing")); <END> } Object id = message.get("id"); if (!(id instanceof String || id instanceof Number || id == null)) { throw new JsonRpcException(null, invalid("key `id` not string or number or null", id)); } else { return id; } }</code><technical_language>circumstances a message a key "id"? (Just noticed this is preexisting code)</technical_language>

Target:
private Object parseId(Map message) throws JsonRpcException { if (!message.containsKey(ID)) { throw new JsonRpcException(null, invalid(String.format("required key `%s` missing", ID))); } Object id = message.get(ID); if (!(id instanceof String || id instanceof Number || id == null)) { throw new JsonRpcException( null, invalid(String.format("key `%s` not string or number or null", ID), id)); } else { return id; } }
Source:
<code>public boolean onHttpResponseReceive(HttpMessage msg) { String site = msg.getRequestHeader().getHostName() + ":" + msg.getRequestHeader().getHostPort(); if (getView() != null) { this.getParamsPanel().addSite(site); } SiteParameters sps = this.getSiteParameters(site); TreeSet<HtmlParameter> params = msg.getCookieParams(); Iterator<HtmlParameter> iter = params.iterator(); while (iter.hasNext()) { persist(sps.addParam(site, iter.next(), msg)); } List<HttpHeaderField> headersList = msg.getResponseHeader().getHeaders(); Iterator<HttpHeaderField> hdrIter = headersList.iterator(); <START> while (hdrIter.hasNext()) { <END> HttpHeaderField hdrField = hdrIter.next(); HtmlParameter headerParam = new HtmlParameter(HtmlParameter.Type.header, hdrField.getName(), hdrField.getValue()); sps.addParam(site, headerParam, msg); } return true; }</code><technical_language>enhanced for (avoids explicit hasNext/next calls)</technical_language>

Target:
public boolean onHttpResponseReceive(HttpMessage msg) { String site = msg.getRequestHeader().getHostName() + ":" + msg.getRequestHeader().getHostPort(); if (getView() != null) { this.getParamsPanel().addSite(site); } SiteParameters sps = this.getSiteParameters(site); TreeSet<HtmlParameter> params = msg.getCookieParams(); Iterator<HtmlParameter> iter = params.iterator(); while (iter.hasNext()) { persist(sps.addParam(site, iter.next(), msg)); } List<HttpHeaderField> headersList = msg.getResponseHeader().getHeaders(); List<String> setCookieHeaders = Arrays.asList(HttpHeader.SET_COOKIE.toLowerCase(), HttpHeader.SET_COOKIE2.toLowerCase()); for (HttpHeaderField hdrField:headersList) { if (setCookieHeaders.contains(hdrField.getName().toLowerCase())) { continue; } HtmlParameter headerParam = new HtmlParameter(HtmlParameter.Type.header, hdrField.getName(), hdrField.getValue()); persist(sps.addParam(site, headerParam, msg)); } return true; }
Source:
<code>public void setup() throws IOException { InputStreamFactory in = new ResourceAsStreamFactory(ADSentenceSampleStreamTest.class, "/opennlp/tools/formats/ad.sample"); try (ADSentenceSampleStream stream = new ADSentenceSampleStream( new PlainTextByLineStream(in, "UTF-8"), true)) { SentenceSample sample = stream.read(); <START> while (sample != null) { <END> System.out.println(sample.getDocument()); System.out.println("<fim>"); samples.add(sample); sample = stream.read(); } } }</code><technical_language>is bad style read a stream, assign in while condition</technical_language>

Target:
public void setup() throws IOException { InputStreamFactory in = new ResourceAsStreamFactory(ADSentenceSampleStreamTest.class, "/opennlp/tools/formats/ad.sample"); try (ADSentenceSampleStream stream = new ADSentenceSampleStream( new PlainTextByLineStream(in, StandardCharsets.UTF_8), true)) { SentenceSample sample; while ((sample = stream.read()) != null) { System.out.println(sample.getDocument()); System.out.println("<fim>"); samples.add(sample); } } }
Source:
<code>public String toString() { <START> return new StringBuilder("Amount{") <END> .append("total=").append(total) .append('}').toString(); }</code><technical_language>@vkdrn Thanks for contributing!! mind add attributes in toString method too</technical_language>

Target:
public String toString() { return new StringBuilder("Amount{") .append("total=").append(total) .append(", fees=").append(fees) .append(", refunds=").append(refunds) .append(", liquid=").append(liquid) .append(", currency='").append(currency) .append('\'') .append('}').toString(); }
Source:
<code>private static ArmorStand getArmorStand(Block projector, boolean createIfNoneExists) { String nametag = BlockStorage.getLocationInfo(projector.getLocation(), "text"); double xOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), X_OFFSET_PARAMETER)); double yOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), Y_OFFSET_PARAMETER)); double zOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), Z_OFFSET_PARAMETER)); <START> Location l = new Location(projector.getWorld(), projector.getX() + xOffset, projector.getY() + yOffset, projector.getZ() + zOffset); <END> for (Entity n : l.getChunk().getEntities()) { if (n instanceof ArmorStand && l.distanceSquared(n.getLocation()) < 0.4) { String customName = n.getCustomName(); if (customName != null && customName.equals(nametag)) { return (ArmorStand) n; } } } if (!createIfNoneExists) { return null; } ArmorStand hologram = SimpleHologram.create(l); hologram.setCustomName(nametag); return hologram; }</code><technical_language>suggestion Location l = projector.getLocation(xOffset, yOffset, zOffset).add();</technical_language>

Target:
private static ArmorStand getArmorStand(Block projector, boolean createIfNoneExists) { String nametag = BlockStorage.getLocationInfo(projector.getLocation(), "text"); double xOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), X_OFFSET_PARAMETER)); double yOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), Y_OFFSET_PARAMETER)); double zOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), Z_OFFSET_PARAMETER)); Location l = projector.getLocation().add(xOffset, yOffset, zOffset); for (Entity n : l.getChunk().getEntities()) { if (n instanceof ArmorStand && l.distanceSquared(n.getLocation()) < 0.4) { String customName = n.getCustomName(); if (customName != null && customName.equals(nametag)) { return (ArmorStand) n; } } } if (!createIfNoneExists) { return null; } ArmorStand hologram = SimpleHologram.create(l); hologram.setCustomName(nametag); return hologram; }
Source:
<code>default Iterator<T> takeRight(int n) { if (n <= 0) { return empty(); } else { final Iterator<T> that = this; return new Iterator<T>() { private Queue<T> queue = Queue.empty(); @Override public boolean hasNext() { while (that.hasNext()) { <START> queue = queue.append(that.next()); <END> if(queue.length() > n) { queue = queue.dequeue()._2; } } return queue.length() > 0; } @Override public T next() { if (!hasNext()) { EMPTY.next(); } final Tuple2<T, Queue<T>> t = queue.dequeue(); queue = t._2; return t._1; } }; } }</code><technical_language>I call queue.enqueue(that.next()) (which is same)</technical_language>

Target:
default Iterator<T> takeRight(int n) { if (n <= 0) { return empty(); } else { final Iterator<T> that = this; return new Iterator<T>() { private Queue<T> queue = Queue.empty(); @Override public boolean hasNext() { while (that.hasNext()) { queue = queue.enqueue(that.next()); if(queue.length() > n) { queue = queue.dequeue()._2; } } return queue.length() > 0; } @Override public T next() { if (!hasNext()) { EMPTY.next(); } final Tuple2<T, Queue<T>> t = queue.dequeue(); queue = t._2; return t._1; } }; } }
Source:
<code>public Set<HivePrivilegeInfo> listTablePrivileges(String databaseName, String tableName, PrestoPrincipal principal) { try { return retry() .stopOnIllegalExceptions() .run("getListPrivileges", stats.getListPrivileges().wrap(() -> { try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) { Table table = client.getTable(databaseName, tableName); <START> ImmutableSet.Builder<HivePrivilegeInfo> privileges = ImmutableSet.builder(); <END> if (principal.getType() == USER && table.getOwner().equals(principal.getName())) { privileges.add(new HivePrivilegeInfo(OWNERSHIP, true, principal)); } List<HiveObjectPrivilege> hiveObjectPrivilegeList = client.listPrivileges( principal.getName(), fromPrestoPrincipalType(principal.getType()), new HiveObjectRef(TABLE, databaseName, tableName, null, null)); for (HiveObjectPrivilege hiveObjectPrivilege : hiveObjectPrivilegeList) { privileges.addAll(parsePrivilege(hiveObjectPrivilege.getGrantInfo())); } return privileges.build(); } })); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }</code><technical_language>Method is invoked triple databaseName, tableName, principal, while table is retrieved for tuple databaseName, tableName. In case of roles this method called role (principal) databaseName, tableName casing retrieval for table. This a problem if table cached, cache table is retrieved times. This planing time long if roles</technical_language>

Target:
public Set<HivePrivilegeInfo> listTablePrivileges(String databaseName, String tableName, PrestoPrincipal principal) { try { return retry() .stopOnIllegalExceptions() .run("getListPrivileges", stats.getListPrivileges().wrap(() -> { try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) { Table table = client.getTable(databaseName, tableName); ImmutableSet.Builder<HivePrivilegeInfo> privileges = ImmutableSet.builder(); List<HiveObjectPrivilege> hiveObjectPrivilegeList; if (principal == null) { hiveObjectPrivilegeList = client.listPrivileges( null, null, new HiveObjectRef(TABLE, databaseName, tableName, null, null)); } else { if (principal.getType() == USER && table.getOwner().equals(principal.getName())) { privileges.add(new HivePrivilegeInfo(OWNERSHIP, true, principal, principal)); } hiveObjectPrivilegeList = client.listPrivileges( principal.getName(), fromPrestoPrincipalType(principal.getType()), new HiveObjectRef(TABLE, databaseName, tableName, null, null)); } for (HiveObjectPrivilege hiveObjectPrivilege : hiveObjectPrivilegeList) { PrestoPrincipal grantee = new PrestoPrincipal(fromMetastoreApiPrincipalType(hiveObjectPrivilege.getPrincipalType()), hiveObjectPrivilege.getPrincipalName()); privileges.addAll(parsePrivilege(hiveObjectPrivilege.getGrantInfo(), Optional.of(grantee))); } return privileges.build(); } })); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }
Source:
<code>public void concurrentUsageTest() throws Exception { final int firstNumber = 1; <START> final int lastNumber = 50; <END> final BigIntegerNumberGenerator generator = createGenerator(); final List<CompletionStage<BigInteger>> completionStageNumbers = IntStream.range(firstNumber, lastNumber) .mapToObj(i -> generator.getNextNumber()) .collect(Collectors.toList()); final List<BigInteger> numbersGenerated = CompletableFutureUtils.listOfFuturesToFutureOfList(completionStageNumbers).toCompletableFuture().join(); final List<BigInteger> expectedNumbers = IntStream.range(firstNumber, lastNumber).mapToObj(i -> BigInteger.valueOf(i)).collect(Collectors.toList()); assertThat(numbersGenerated.containsAll(expectedNumbers)).isTrue(); }</code><technical_language>change that</technical_language>

Target:
public void concurrentUsageTest() throws Exception { final int firstNumber = 1; final int lastNumber = 20; final BigIntegerNumberGenerator generator = createGenerator(); final List<CompletionStage<BigInteger>> completionStageNumbers = IntStream.range(firstNumber, lastNumber) .mapToObj(i -> generator.getNextNumber()) .collect(Collectors.toList()); final List<BigInteger> numbersGenerated = CompletableFutureUtils.listOfFuturesToFutureOfList(completionStageNumbers).toCompletableFuture().join(); final List<BigInteger> expectedNumbers = IntStream.range(firstNumber, lastNumber).mapToObj(i -> BigInteger.valueOf(i)).collect(Collectors.toList()); assertThat(numbersGenerated.containsAll(expectedNumbers)).isTrue(); }
Source:
<code>public void processTaskState(Task task) { long workItemId = task.getTaskData().getWorkItemId(); long processInstanceId = task.getTaskData().getProcessInstanceId(); RuntimeManager manager = getManager(task); RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId)); KieSession session = runtime.getKieSession(); if (task.getTaskData().getStatus() == Status.Completed) { String userId = task.getTaskData().getActualOwner().getId(); Map<String, Object> results = new HashMap<String, Object>(); Map<String, Object> taskOutcome = task.getTaskData().getTaskOutputVariables(); if (taskOutcome != null) { <START> results.putAll(taskOutcome); <END> } predictionService.train(task, task.getTaskData().getTaskInputVariables(), results); session.getWorkItemManager().completeWorkItem(workItemId, results); } else { session.getWorkItemManager().abortWorkItem(workItemId); } }</code><technical_language>this removed? Is included in taskOutcome</technical_language>

Target:
public void processTaskState(Task task) { long workItemId = task.getTaskData().getWorkItemId(); long processInstanceId = task.getTaskData().getProcessInstanceId(); RuntimeManager manager = getManager(task); RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId)); KieSession session = runtime.getKieSession(); if (task.getTaskData().getStatus() == Status.Completed) { String userId = task.getTaskData().getActualOwner().getId(); Map<String, Object> results = new HashMap<String, Object>(); Map<String, Object> taskOutcome = task.getTaskData().getTaskOutputVariables(); if (taskOutcome != null) { results.putAll(taskOutcome); } results.put("ActorId", userId); predictionService.train(task, task.getTaskData().getTaskInputVariables(), results); session.getWorkItemManager().completeWorkItem(workItemId, results); } else { session.getWorkItemManager().abortWorkItem(workItemId); } }
Source:
<code>public void run() { appendMsgToCustomLog("Started NodeRecycleThread to restart the node once all the sessions are completed."); <START> while (getTotalUsed() > 1) { <END> try { Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } appendMsgToCustomLog("All sessions are completed and restarting the node."); shutdownNode(); }</code><technical_language>want wait getTotalUsed is >0 instead? I.e "last" session timeout</technical_language>

Target:
public void run() { appendMsgToCustomLog("Started NodeRecycleThread to restart the node once all the sessions are completed."); while (getTotalUsed() > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } appendMsgToCustomLog("All sessions are completed and restarting the node."); shutdownNode(); }
Source:
<code>public void initialize() { logger.debug("Initializing hue light handler."); final String configLightId = (String) getConfig().get(LIGHT_ID); if (configLightId != null) { lightId = configLightId; if (getHueBridgeHandler() != null) { ThingStatusInfo statusInfo = getBridge().getStatusInfo(); updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription()); FullLight fullLight = getLight(); if (fullLight != null) { updateProperty(Thing.PROPERTY_FIRMWARE_VERSION, fullLight.getSoftwareVersion()); <START> String thingUID = HueBindingConstants.THING_TYPE_PAR16_50_TW.getId(); <END> if (thingUID.equals("PAR16_50_TW")) { isOsramPar16 = true; } } } } }</code><technical_language>Please rename thingTypeId, UID is defined fully qualified name colons in is id of type, of thing</technical_language>

Target:
public void initialize() { logger.debug("Initializing hue light handler."); final String configLightId = (String) getConfig().get(LIGHT_ID); if (configLightId != null) { lightId = configLightId; if (getHueBridgeHandler() != null) { ThingStatusInfo statusInfo = getBridge().getStatusInfo(); updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription()); FullLight fullLight = getLight(); if (fullLight != null) { updateProperty(Thing.PROPERTY_FIRMWARE_VERSION, fullLight.getSoftwareVersion()); String thingTypeId = HueBindingConstants.THING_TYPE_PAR16_50_TW.getId(); if (thingTypeId.equals("PAR16_50_TW")) { isOsramPar16 = true; } } } } }
Source:
<code>JoinType(int val) { assert (this.ordinal() == val) : "Enum element " + this.name() + " in position " + this.ordinal() + " instead of position " + val; <START> m_val = val; <END> }</code><technical_language>if m_val equal ordinal bother storing ordinal everywhere</technical_language>

Target:
JoinType(int val) { assert (this.ordinal() == val) : "Enum element " + this.name() + " in position " + this.ordinal() + " instead of position " + val; }
Source:
<code>public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addSelfLink(); <START> <END> } if (rep instanceof DefaultRepresentation || rep instanceof FullRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("identifierType"); description.addProperty("location"); description.addProperty("source"); description.addProperty("manualEntryEnabled"); description.addProperty("automaticGenerationEnabled"); description.addSelfLink(); if (rep instanceof DefaultRepresentation) { description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } } return description; }</code><technical_language>unnecessary space</technical_language>

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addSelfLink(); } else if (rep instanceof DefaultRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("identifierType"); description.addProperty("location"); description.addProperty("source"); description.addProperty("manualEntryEnabled"); description.addProperty("automaticGenerationEnabled"); description.addSelfLink(); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } else if (rep instanceof FullRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("identifierType"); description.addProperty("location"); description.addProperty("source"); description.addProperty("manualEntryEnabled"); description.addProperty("automaticGenerationEnabled"); description.addSelfLink(); } return description; }
Source:
<code>private <T> T callWithTimeLimit(Callable<T> callable, LockRequestSpecification specification) throws InterruptedException { try { return timeLimiter.callWithTimeout(callable, blockingTimeLimitMillis, TimeUnit.MILLISECONDS, true); } catch (InterruptedException e) { log.warn("Lock service was interrupted when servicing for client \"{}\"; request was {}", specification.method(), specification.client(), specification.lockRequest(), e); throw e; } catch (UncheckedTimeoutException e) { String errorMessage = String.format( "Lock service timed out after %s milliseconds when servicing %s for client \"%s\"; request was %s", blockingTimeLimitMillis, specification.method(), specification.client(), specification.lockRequest()); <START> log.warn(errorMessage, e); <END> throw new BlockingTimeoutException(errorMessage); } catch (Exception e) { throw Throwables.propagate(e); } }</code><technical_language>a problem, expect time out occasionally. a small number of in logs issue investigate find ways optimise products. This points INFO. If this is happening a huge number of times is a problem, I expect this clear volume. If downgrade info change variable message errorMessage, moving alarm read code</technical_language>

Target:
private <T> T callWithTimeLimit(Callable<T> callable, LockRequestSpecification specification) throws InterruptedException { try { return timeLimiter.callWithTimeout(callable, blockingTimeLimitMillis, TimeUnit.MILLISECONDS, true); } catch (InterruptedException e) { log.info("Lock service was interrupted when servicing for client \"{}\"; request was {}", specification.method(), specification.client(), specification.lockRequest(), e); throw e; } catch (UncheckedTimeoutException e) { String message = String.format( "Lock service timed out after %s milliseconds when servicing %s for client \"%s\"; request was %s", blockingTimeLimitMillis, specification.method(), specification.client(), specification.lockRequest()); log.info(message, e); throw new BlockingTimeoutException(message); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
<code>LocalSymbolTableImports(SymbolTable defaultSystemSymtab, SymbolTable... imports) { assert defaultSystemSymtab.isSystemTable() : "defaultSystemSymtab isn't a system symtab"; if (imports != null && imports.length > 0) { if (imports[0].isSystemTable()) { myImports = new SymbolTable[imports.length]; <START> System.arraycopy(imports, 0, myImports, 0, imports.length); <END> } else { myImports = new SymbolTable[imports.length + 1]; myImports[0] = defaultSystemSymtab; System.arraycopy(imports, 0, myImports, 1, imports.length); } } else { myImports = new SymbolTable[] { defaultSystemSymtab }; } myBaseSids = new int[myImports.length]; myMaxId = prepBaseSids(myBaseSids, myImports); }</code><technical_language>this is a shallow copy, I achieve clone()ing array</technical_language>

Target:
LocalSymbolTableImports(SymbolTable defaultSystemSymtab, SymbolTable... imports) { assert defaultSystemSymtab.isSystemTable() : "defaultSystemSymtab isn't a system symtab"; if (imports != null && imports.length > 0) { if (imports[0].isSystemTable()) { myImports = imports.clone(); } else { myImports = new SymbolTable[imports.length + 1]; myImports[0] = defaultSystemSymtab; System.arraycopy(imports, 0, myImports, 1, imports.length); } } else { myImports = new SymbolTable[] { defaultSystemSymtab }; } myBaseSids = new int[myImports.length]; myMaxId = prepBaseSids(myBaseSids, myImports); }
Source:
<code>private void recordImmutableTimestamp(long immutableTs) { long recentTs = recentImmutableTs.get(); while (recentTs < immutableTs) { if (recentImmutableTs.compareAndSet(recentTs, immutableTs)) { break; } else { recentTs = recentImmutableTs.get(); <START> } <END> } }</code><technical_language>nit: I need else block here, break out of while loop</technical_language>

Target:
private void recordImmutableTimestamp(long immutableTs) { recentImmutableTs.updateAndGet(current -> Math.max(current, immutableTs)); }
Source:
<code>private boolean importTraces() { boolean success = false; IOverwriteQuery overwriteQuery = new IOverwriteQuery() { @Override public String queryOverwrite(String file) { return fOverwrite ? IOverwriteQuery.ALL : IOverwriteQuery.NO_ALL; } }; FileSystemStructureProvider fileSystemStructureProvider = FileSystemStructureProvider.INSTANCE; for (FileAndName traceToImport : fTraces) { try { if (fLinked) { createLink(fTargetFolder, Path.fromOSString(traceToImport.getFile().getAbsolutePath()), traceToImport.getName()); setTraceType(traceToImport); success = true; } else { List<File> subList = new ArrayList<File>(); subList.add(traceToImport.getFile()); ImportOperation operation = new ImportOperation(getContainerFullPath().append(traceToImport.getName()), traceToImport.getFile().getParentFile(), fileSystemStructureProvider, overwriteQuery, subList); operation.setContext(getShell()); operation.setCreateLinks(fLinked); if (executeImportOperation(operation)) { setTraceType(traceToImport); success = true; } } } catch (Exception e) { <START> e.printStackTrace(); <END> } } return success; }</code><technical_language>e.printStackTrace(). dialog box or/and log error log of plugin</technical_language>

Target:
private boolean importTraces() { boolean success = false; IOverwriteQuery overwriteQuery = new IOverwriteQuery() { @Override public String queryOverwrite(String file) { return fOverwrite ? IOverwriteQuery.ALL : IOverwriteQuery.NO_ALL; } }; FileSystemStructureProvider fileSystemStructureProvider = FileSystemStructureProvider.INSTANCE; for (FileAndName traceToImport : fTraces) { try { if (fLinked) { createLink(fTargetFolder, Path.fromOSString(traceToImport.getFile().getAbsolutePath()), traceToImport.getName()); setTraceType(traceToImport); success = true; } else { List<File> subList = new ArrayList<File>(); subList.add(traceToImport.getFile()); ImportOperation operation = new ImportOperation(getContainerFullPath().append(traceToImport.getName()), traceToImport.getFile().getParentFile(), fileSystemStructureProvider, overwriteQuery, subList); operation.setContext(getShell()); operation.setCreateLinks(fLinked); if (executeImportOperation(operation)) { setTraceType(traceToImport); success = true; } } } catch (Exception e) { } } return success; }
Source:
<code>private Object processPreStoredProcQuery(InternalParamCollection params, int queryLevel) throws DataServiceFault { boolean isError = false; CallableStatement stmt = null; ResultSet rs = null; try { Connection conn = this.createConnection(queryLevel); stmt = (CallableStatement) this.createProcessedPreparedStatement( SQLQuery.DS_QUERY_TYPE_STORED_PROC, params, conn); if (this.isJDBCFirstBatchRequest()) { this.setBatchPreparedStatement(stmt); BatchDataServiceRequest.addParticipant(this); } if (!this.hasResult() || (this.hasResult() && this.isReturnGeneratedKeys()) || (this.hasResult() && this.isReturnUpdatedRowCount())) { if (this.isJDBCBatchRequest()) { if (this.isJDBCLastBatchRequest()) { stmt.executeBatch(); } } else { stmt.executeUpdate(); } } else { if (this.isResultOnlyOutParams()) { stmt.execute(); if (this.hasRefCursor()) { rs = (ResultSet) stmt.getObject(getCurrentRefCursorOrdinal()); } } else { rs = this.getFirstRSOfStoredProc(stmt); } } return new QueryResultInfo(stmt, rs); } catch (Exception e) { log.error(e.getMessage(), e); isError = true; throw new DataServiceFault(e, FaultCodes.DATABASE_ERROR, "Error in 'SQLQuery.processStoredProcQuery': " + e.getMessage()); } finally { <START> if (log.isDebugEnabled()){ <END> log.debug("Stopping DB calls. ThreadID:" + Thread.currentThread().getId()); } if (isError) { this.releaseResources(rs, this.isStatementClosable(isError) ? stmt : null); } } }</code><technical_language>Fix code formatting</technical_language>

Target:
private Object processPreStoredProcQuery(InternalParamCollection params, int queryLevel) throws DataServiceFault { boolean isError = false; CallableStatement stmt = null; ResultSet rs = null; try { Connection conn = this.createConnection(queryLevel); stmt = (CallableStatement) this.createProcessedPreparedStatement( SQLQuery.DS_QUERY_TYPE_STORED_PROC, params, conn); if (this.isJDBCFirstBatchRequest()) { this.setBatchPreparedStatement(stmt); BatchDataServiceRequest.addParticipant(this); } if (!this.hasResult() || (this.hasResult() && this.isReturnGeneratedKeys()) || (this.hasResult() && this.isReturnUpdatedRowCount())) { if (this.isJDBCBatchRequest()) { if (this.isJDBCLastBatchRequest()) { stmt.executeBatch(); } } else { stmt.executeUpdate(); } } else { if (this.isResultOnlyOutParams()) { stmt.execute(); if (this.hasRefCursor()) { rs = (ResultSet) stmt.getObject(getCurrentRefCursorOrdinal()); } } else { rs = this.getFirstRSOfStoredProc(stmt); } } return new QueryResultInfo(stmt, rs); } catch (Exception e) { log.error(e.getMessage(), e); isError = true; throw new DataServiceFault(e, FaultCodes.DATABASE_ERROR, "Error in 'SQLQuery.processStoredProcQuery': " + e.getMessage()); } finally { if (log.isDebugEnabled()) { log.debug("Stopping DB calls: ThreadID - " + Thread.currentThread().getId()); } if (isError) { this.releaseResources(rs, this.isStatementClosable(isError) ? stmt : null); } } }
Source:
<code>public void flush(FlushMode mode) { for (ConnectionListener cl : listeners) { <START> if (FlushMode.ALL == mode) <END> { destroyAndRemoveConnectionListener(cl); } if (FlushMode.INVALID == mode && cl.getState() != DESTROY && cl.getState() != DESTROYED) { int previousState = cl.getState(); cl.changeState(previousState, VALIDATION); validateConnectionListener(cl, previousState); } if (FlushMode.IDLE == mode && (cl.getState() == FREE || cl.getState() == TO_POOL) || cl.getState() == DESTROY) { destroyAndRemoveConnectionListener(cl); } } prefill(); }</code><technical_language>do "if / else if / else if" style</technical_language>

Target:
public void flush(FlushMode mode) { for (ConnectionListener cl : listeners) { switch (mode) { case ALL: { destroyAndRemoveConnectionListener(cl, listeners); break; } case INVALID: { if (cl.changeState(FREE, VALIDATION)) { validateConnectionListener(listeners, cl, FREE); } break; } case IDLE: { if (cl.changeState(FREE, FLUSH)) { destroyAndRemoveConnectionListener(cl, listeners); } break; } case GRACEFULLY: { if (cl.changeState(FREE, FLUSH)) { destroyAndRemoveConnectionListener(cl, listeners); } else if (cl.getState() == IN_USE || cl.getState() == TO_POOL || cl.getState() == VALIDATION) { cl.setState(DESTROY); } break; } } } prefill(); }
Source:
<code>public void execute(IAction action) { boolean performAction = MessageDialog.openConfirm(getShell(), UIText.DiscardChangesAction_confirmActionTitle, UIText.DiscardChangesAction_confirmActionMessage); if (!performAction) return; String jobname = UIText.DiscardChangesAction_discardChanges; Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { new DiscardChangesOperation(getSelectedResources()) .execute(monitor); } catch (CoreException e) { return Activator.createErrorStatus( e.getStatus().getMessage(), e); } return Status.OK_STATUS; } <START> }; <END> job.setUser(true); job.schedule(); }</code><technical_language>set a scheduling rule for job based resources</technical_language>

Target:
public void execute(IAction action) { boolean performAction = MessageDialog.openConfirm(getShell(), UIText.DiscardChangesAction_confirmActionTitle, UIText.DiscardChangesAction_confirmActionMessage); if (!performAction) return; final DiscardChangesOperation operation = new DiscardChangesOperation( getSelectedResources()); String jobname = UIText.DiscardChangesAction_discardChanges; Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { operation.execute(monitor); } catch (CoreException e) { return Activator.createErrorStatus(e.getStatus() .getMessage(), e); } return Status.OK_STATUS; } }; job.setUser(true); job.setRule(operation.getSchedulingRule()); job.schedule(); }