auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean isField(ExpressionTree tree) { TypeSymbol enclosingClass = (TypeSymbol) getSemanticModel().getEnclosingClass(tree); <START> if (tree.is(Kind.IDENTIFIER)) { <END> IdentifierTree identifier = (IdentifierTree) tree; List<Symbol> lookup = ((TypeSymbol) enclosingClass).members().lookup(identifier.name()); Symbol reference = getSemanticModel().getReference(identifier); return lookup.contains(reference); } return false; }</code><technical_language>this.myField ? This isField method return referenced symbol</technical_language>

Target:
private boolean isField(ExpressionTree tree) { if (tree.is(Kind.IDENTIFIER)) { Symbol reference = getSemanticModel().getReference((IdentifierTree) tree); return reference != null && reference.owner().isKind(Symbol.TYP); } else if (tree.is(Kind.MEMBER_SELECT)) { MemberSelectExpressionTree mse = (MemberSelectExpressionTree) tree; ExpressionTree mseExpression = mse.expression(); if (isThis(mseExpression)) { return isField(mse.identifier()); } else { return isField(mseExpression); } } return false; }
Source:
<code>protected Promise<List<Node>> getChildrenImpl() { List<Node> fileNodes = new ArrayList<>(); List<SearchOccurrence> occurrences = searchResult.getOccurrences(); occurrences.sort(Comparator.comparingInt((SearchOccurrence searchOccurrence) -> searchOccurrence.getLineNumber())); for (SearchOccurrence occurrence : occurrences) { <START> FoundOccurrenceNode foundItemNode = nodeFactory.newFoundOccurrenceNode(occurrence, searchResult.getPath(), searchResult.getContentUrl()); <END> fileNodes.add(foundItemNode); } return promiseProvider.resolve(fileNodes); }</code><technical_language>simplified (SearchOccurrence searchOccurrence) -> searchOccurrence.getLineNumber()) -> SearchOccurrence::getLineNumber</technical_language>

Target:
protected Promise<List<Node>> getChildrenImpl() { List<Node> fileNodes; List<SearchOccurrence> occurrences = searchResult.getOccurrences(); occurrences.sort(Comparator.comparingInt((SearchOccurrence searchOccurrence) -> searchOccurrence.getLineNumber())); fileNodes = occurrences.stream().map(occurrence -> nodeFactory .newFoundOccurrenceNode(occurrence, searchResult.getPath())).collect(Collectors.toList()); return promiseProvider.resolve(fileNodes); }
Source:
<code><START> protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2, Rectangle2D drawArea, boolean vertical) { <END> RectangleInsets insets = getTickLabelInsets(); double maxWidth = 0.0; Iterator iterator = ticks.iterator(); while (iterator.hasNext()) { Tick tick = (Tick) iterator.next(); Rectangle2D labelBounds = null; if (tick.getText() != null) { labelBounds = TextUtilities.calculateRotatedStringBounds(tick.getText(), g2, 0, 0, TextAnchor.TOP_LEFT, tickLabelAngle, TextAnchor.TOP_LEFT).getBounds2D(); } if (labelBounds != null && labelBounds.getWidth() + insets.getLeft() + insets.getRight() > maxWidth) { maxWidth = labelBounds.getWidth() + insets.getLeft() + insets.getRight(); } } return maxWidth; }</code><technical_language>findMaximumTickLabelWidth & findMaximumTickLabelHeight identical PercentileLogAxis.findMaximumTickLabelWidth & PercentileLogAxis.findMaximumTickLabelHeight. extracted some other class (e.g. AxisUtils)</technical_language>

Target:
protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2, Rectangle2D drawArea, boolean vertical) { return ChartsHelper.getMaximumTickLabelWidth(ticks, g2, getTickLabelInsets(), getTickLabelFont(), tickLabelAngle); }
Source:
<code>private Set<ResolvedBroadcast> aggregateBroadcastsInternal(Collection<ResolvedBroadcast> broadcasts) { Multimap<ChannelRef, ResolvedBroadcast> parentChannelMap = broadcasts.stream() .collect(MoreCollectors.toImmutableListMultiMap( resolvedBroadcast -> MoreObjects.firstNonNull( resolvedBroadcast.getResolvedChannel() .getChannel() .getParent(), <START> new ChannelRef( <END> resolvedBroadcast.getResolvedChannel().getChannel().getId(), resolvedBroadcast.getResolvedChannel().getChannel().getSource() ) ), resolvedBroadcast -> resolvedBroadcast )); Set<ResolvedBroadcast> resolvedBroadcasts = Sets.newHashSet(); for (ChannelRef channelRef : parentChannelMap.keySet()) { resolvedBroadcasts.add( aggregateChannelsFromParent(channelRef, parentChannelMap.get(channelRef)) ); } return resolvedBroadcasts; }</code><technical_language>a Channel#toRef method convert a channel ref. add useful elsewhere</technical_language>

Target:
private Set<ResolvedBroadcast> aggregateBroadcastsInternal(Collection<ResolvedBroadcast> broadcasts) { Multimap<ChannelRef, ResolvedBroadcast> parentChannelMap = broadcasts.stream() .collect(MoreCollectors.toImmutableListMultiMap( resolvedBroadcast -> MoreObjects.firstNonNull( resolvedBroadcast.getResolvedChannel() .getChannel() .getParent(), resolvedBroadcast.getResolvedChannel() .getChannel() .toRef() ), resolvedBroadcast -> resolvedBroadcast )); Set<ResolvedBroadcast> resolvedBroadcasts = Sets.newHashSet(); for (ChannelRef channelRef : parentChannelMap.keySet()) { resolvedBroadcasts.add( aggregateChannelsFromParent(channelRef, parentChannelMap.get(channelRef)) ); } return resolvedBroadcasts; }
Source:
<code>private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; <START> if (this.key == null) { <END> try { if (keyCollection.equals(SECRETS_COLLECTION)) { this.key = getSecretKey().block(); } else { KeyVaultKey keyVaultKey = getKey().block(); this.key = keyVaultKey.getKey(); } keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.warning("Failed to retrieve key from key vault"); logger.logExceptionAsWarning(e); keyAvailableLocally = false; } } return keyAvailableLocally; }</code><technical_language>do want a check for keyCollection</technical_language>

Target:
private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if (this.key == null && keyCollection != null) { try { if (keyCollection.equals(SECRETS_COLLECTION)) { this.key = getSecretKey().block(); } else { KeyVaultKey keyVaultKey = getKey().block(); this.key = keyVaultKey.getKey(); } keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.warning("Failed to retrieve key from key vault"); logger.logExceptionAsWarning(e); keyAvailableLocally = false; } } return keyAvailableLocally; }
Source:
<code>protected Function<GridCellTuple, Command> newCellHasNoValueCommand() { <START> return (gc) -> new DeleteCellValueCommand(gc, <END> () -> uiModelMapper, gridLayer::batch); }</code><technical_language>I this code moved, worth more descriptive variable name gc know</technical_language>

Target:
protected Function<GridCellTuple, Command> newCellHasNoValueCommand() { return (gridCellTuple) -> new DeleteCellValueCommand(gridCellTuple, () -> uiModelMapper, gridLayer::batch); }
Source:
<code>static String switchToAllVolumes(Path olddelete) { <START> if (olddelete.depth() == 4 && !olddelete.getName().startsWith(Constants.BULK_PREFIX)) { <END> return GcVolumeUtil.getDeleteTabletOnAllVolumesUri( TableId.of(olddelete.getParent().getName()), olddelete.getName()); } else { return olddelete.toString(); } }</code><technical_language>Volumes do depth of 1. For example a user configure a volume hdfs://localhost:9000/dev/accumulo. This a dir volume a depth != 4</technical_language>

Target:
static String switchToAllVolumes(Path olddelete) { Path pathNoVolume = Objects.requireNonNull(VolumeManager.FileType.TABLE.removeVolume(olddelete), "Invalid delete marker. No volume in path: " + olddelete); if (pathNoVolume.depth() == 3 && !pathNoVolume.getName().startsWith(Constants.BULK_PREFIX)) { return GcVolumeUtil.getDeleteTabletOnAllVolumesUri( TableId.of(pathNoVolume.getParent().getName()), pathNoVolume.getName()); } else { return olddelete.toString(); } }
Source:
<code>public <T> T get(Object key, Callable<T> valueLoader) { Object value = map.get(key); if (value == null) { <START> misses.incrementAndGet(); <END> RLock lock = map.getLock(key); lock.lock(); try { value = map.get(key); if (value == null) { try { value = toStoreValue(valueLoader.call()); } catch (Exception ex) { try { Class<?> c = Class.forName("org.springframework.cache.Cache$ValueRetrievalException"); Constructor<?> constructor = c.getConstructor(Object.class, Callable.class, Throwable.class); RuntimeException exception = (RuntimeException) constructor.newInstance(key, valueLoader, ex.getCause()); throw exception; } catch (Exception e) { throw new IllegalStateException(e); } } map.put(key, value); } } finally { lock.unlock(); } }else{ addCacheHit(); } return (T) fromStoreValue(value); }</code><technical_language>@candrews Please replace addCacheMiss() method</technical_language>

Target:
public <T> T get(Object key, Callable<T> valueLoader) { Object value = map.get(key); if (value == null) { addCacheMiss(); RLock lock = map.getLock(key); lock.lock(); try { value = map.get(key); if (value == null) { try { value = toStoreValue(valueLoader.call()); } catch (Exception ex) { try { Class<?> c = Class.forName("org.springframework.cache.Cache$ValueRetrievalException"); Constructor<?> constructor = c.getConstructor(Object.class, Callable.class, Throwable.class); RuntimeException exception = (RuntimeException) constructor.newInstance(key, valueLoader, ex.getCause()); throw exception; } catch (Exception e) { throw new IllegalStateException(e); } } map.put(key, value); } } finally { lock.unlock(); } }else{ addCacheHit(); } return (T) fromStoreValue(value); }
Source:
<code>public void correctPrincipalNoPassword() throws Exception { Owner owner = new Owner("user", "user"); setUserAndPassword("user", ""); <START> when(userService.validateUser("user", "")).thenReturn(true); <END> Set<OwnerPermission> permissions = new HashSet<OwnerPermission>(); permissions.add(new OwnerPermission(owner, Access.ALL)); when(userService.findByLogin("user")).thenReturn(new User()); UserPrincipal expected = new UserPrincipal("user", new ArrayList<Permission>(permissions), false); assertEquals(expected, this.auth.getPrincipal(request)); }</code><technical_language>I this method null in case. I this test is testing empty string is a valid password. fix handle cases though</technical_language>

Target:
public void correctPrincipalNoPassword() throws Exception { Owner owner = new Owner("user", "user"); setUserNoPassword("user"); when(userService.validateUser("user", null)).thenReturn(true); Set<OwnerPermission> permissions = new HashSet<OwnerPermission>(); permissions.add(new OwnerPermission(owner, Access.ALL)); when(userService.findByLogin("user")).thenReturn(new User()); UserPrincipal expected = new UserPrincipal("user", new ArrayList<Permission>(permissions), false); assertEquals(expected, this.auth.getPrincipal(request)); }
Source:
<code>private void dumpHtmlCodeFromTheCurrentPage(ITestResult result, SeleniumWebDriver webDriver) { String testName = result.getTestClass().getName() + "." + result.getMethod().getMethodName(); String filename = NameGenerator.generate(testName + "_", 8) + ".png"; try { String pageSource = webDriver.getPageSource(); Path dmpDirectory = Paths.get("target/htmldump", filename + ".html"); Files.createDirectories(dmpDirectory.getParent()); Files.write(dmpDirectory, pageSource.getBytes(), StandardOpenOption.CREATE); } catch (WebDriverException | IOException e) { <START> LOG.error(format("Can't capture screenshot for test %s", testName), e); <END> } }</code><technical_language>capture dump</technical_language>

Target:
private void dumpHtmlCodeFromTheCurrentPage(ITestResult result, SeleniumWebDriver webDriver) { String testName = result.getTestClass().getName() + "." + result.getMethod().getMethodName(); String filename = NameGenerator.generate(testName + "_", 8) + ".html"; try { String pageSource = webDriver.getPageSource(); Path dmpDirectory = Paths.get("target/htmldump", filename); Files.createDirectories(dmpDirectory.getParent()); Files.write(dmpDirectory, pageSource.getBytes(), StandardOpenOption.CREATE); } catch (WebDriverException | IOException e) { LOG.error(format("Can't dump of html source for test %s", testName), e); } }
Source:
<code>public <T> T getInterface(@Nullable Class<T> policy) { if (policy == null) { return null; } ProxyPolicy proxyPolicy = proxiesByPolicyClass.get(policy); if (proxyPolicy == null) { if (behaviour instanceof NoOpBehaviour) { ProxyPolicyInvocationHandler proxyHandler = new ProxyPolicyInvocationHandler(null, this.behaviour, this.timer); Object proxy = Proxy .newProxyInstance(this.getClass().getClassLoader(), new Class[]{policy}, proxyHandler); <START> if (proxy == null) { <END> throw new IllegalStateException("proxy is null"); } proxyPolicy = new ProxyPolicy(proxy, proxyHandler); } else { Object originalHandler = this.behaviour.getInterface(policy); ProxyPolicyInvocationHandler proxyHandler = new ProxyPolicyInvocationHandler(originalHandler, this.behaviour, this.timer); Object proxy = Proxy .newProxyInstance(this.getClass().getClassLoader(), new Class[]{policy}, proxyHandler); if (proxy == null) { throw new IllegalStateException("proxy is null"); } proxyPolicy = new ProxyPolicy(proxy, proxyHandler); } proxiesByPolicyClass.put(policy, proxyPolicy); } return (T) proxyPolicy.getProxy(); }</code><technical_language>Proxy.newProxyInstance(...) returns null <LINK_0></technical_language>

Target:
public <T> T getInterface(@Nullable Class<T> policy) { if (policy == null) { return null; } ProxyPolicy proxyPolicy = proxiesByPolicyClass.get(policy); if (proxyPolicy == null) { if (behaviour instanceof NoOpBehaviour) { ProxyPolicyInvocationHandler proxyHandler = new ProxyPolicyInvocationHandler(null, this.behaviour, this.timer); Object proxy = Proxy .newProxyInstance(this.getClass().getClassLoader(), new Class[]{policy}, proxyHandler); proxyPolicy = new ProxyPolicy(proxy, proxyHandler); } else { Object originalHandler = this.behaviour.getInterface(policy); ProxyPolicyInvocationHandler proxyHandler = new ProxyPolicyInvocationHandler(originalHandler, this.behaviour, this.timer); Object proxy = Proxy .newProxyInstance(this.getClass().getClassLoader(), new Class[]{policy}, proxyHandler); proxyPolicy = new ProxyPolicy(proxy, proxyHandler); } proxiesByPolicyClass.put(policy, proxyPolicy); } return (T) proxyPolicy.getProxy(); }
Source:
<code>public SpongeFlyingData(boolean value) { <START> super(FlyingData.class, value, Keys.IS_FLYING, ImmutableFlyingData.class); <END> }</code><technical_language>argument needs ImmutableSpongeFlyingData.class</technical_language>

Target:
public SpongeFlyingData(boolean value) { super(FlyingData.class, value, Keys.IS_FLYING, ImmutableSpongeFlyingData.class); }
Source:
<code>default Set<AABB> getIntersectingCollisionBoxes(Entity owner) { <START> return owner.getBoundingBox(). <END> map(box -> getIntersectingCollisionBoxes(owner, box)). orElse(Collections.emptySet()); }</code><technical_language>checkNotNull(owner, "owner") dots beginning of next line, end of previous line</technical_language>

Target:
default Set<AABB> getIntersectingCollisionBoxes(Entity owner) { checkNotNull(owner, "owner"); return owner.getBoundingBox(). map(box -> getIntersectingCollisionBoxes(owner, box)). orElse(Collections.emptySet()); }
Source:
<code>private static Response putBody(HttpPut httpRequest, String body, ContentType contentType, String username, String password) throws URISyntaxException, HttpException { StringEntity stringEntity = new StringEntity(body, contentType); stringEntity.setChunked(true); <START> httpRequest.setEntity(stringEntity); <END> return send(httpRequest, username, password); }</code><technical_language>introduce a condition checks for a not-null ContentType</technical_language>

Target:
private static Response putBody(HttpPut httpRequest, String body, ContentType contentType, String username, String password) throws URISyntaxException, HttpException { if (contentType != null && !StringUtils.isEmpty(body)) { StringEntity stringEntity = new StringEntity(body, contentType); stringEntity.setChunked(true); httpRequest.setEntity(stringEntity); } return send(httpRequest, username, password); }
Source:
<code><START> public MetaFilterView() { <END> super(); GridLayout gridLayout = new GridLayout(5, 2); this.setLayout(gridLayout); JLabel hivLabel = new JLabel("HIV status:"); hivStatus = new JComboBox<>(new DefaultComboBoxModel(new String[] {"- None -", "Positive", "Negative"})); this.add(hivLabel); this.add(hivStatus); JLabel ageLabel = new JLabel("Age or age range:"); age = new JTextField(); this.add(ageLabel); this.add(age); JLabel genderLabel = new JLabel("Gender:"); gender = new JComboBox<>(new DefaultComboBoxModel(new String[] {"- None -", "Male", "Female"})); this.add(genderLabel); this.add(gender); JLabel locationLabel = new JLabel("Location:"); strainLocation = new JTextField(); this.add(locationLabel); this.add(strainLocation); JLabel isolationDateLabel = new JLabel("Isolation date:"); isolationDate = new JTextField(); this.add(isolationDateLabel); this.add(isolationDate); AutoCompleteDecorator.decorate(gender); }</code><technical_language>Large constructor. some smaller methods create fields</technical_language>

Target:
public MetaFilterView() { super(); GridLayout gridLayout = new GridLayout(5, 2); this.setLayout(gridLayout); createHivStatusElements(); createAgeElements(); createGenderElements(); createLocationElements(); createIsolationDateElements(); AutoCompleteDecorator.decorate(gender); }
Source:
<code>public void connect( String channelConfig ) throws IOException { if ( !canUse( channelConfig ) ) { throw new MalformedURLException( "Unknown chanel string " + channelConfig ); } try { <START> URI uri = new URI( channelConfig ); <END> channel = SocketChannel.open( new InetSocketAddress( uri.getHost(), uri.getPort() ) ); } catch ( URISyntaxException e ) { throw new IOException( e.getLocalizedMessage(), e ); } }</code><technical_language>get token 'querystring' issue initial HELO message</technical_language>

Target:
public void connect( String channelConfig ) throws IOException { if ( !canUse( channelConfig ) ) { throw new MalformedURLException( "Unknown chanel string " + channelConfig ); } try { URI uri = new URI( channelConfig ); InetSocketAddress hostAddress = new InetSocketAddress( uri.getHost(), uri.getPort() ); clientSocketChannel = open( withFixedThreadPool( 2, newDaemonThreadFactory() ) ); setTrueOptions( SO_REUSEADDR, TCP_NODELAY, SO_KEEPALIVE ); clientSocketChannel.connect( hostAddress ).get(); } catch ( URISyntaxException | InterruptedException e ) { throw new IOException( e.getLocalizedMessage(), e ); } catch ( ExecutionException e ) { throw new IOException( e.getLocalizedMessage(), e.getCause() ); } }
Source:
<code>public void loadTemplate() throws IOException { DefaultTemplateLoader defaultTemplateLoader = new DefaultTemplateLoader(); String template = defaultTemplateLoader.load(new Version(6,4,1) , "/eventsIndexTemplate"); final JsonElement json = new JsonParser().parse(template); if (!json.isJsonObject()) { throw new IllegalArgumentException("Provided template is not a valid json object"); } JsonObject templateJson = json.getAsJsonObject(); assertNotNull(templateJson); <START> assertTrue(!templateJson.toString().isEmpty()); <END> }</code><technical_language>suggestion assertFalse(templateJson.toString().isEmpty());</technical_language>

Target:
public void loadTemplate() throws IOException { DefaultTemplateLoader defaultTemplateLoader = new DefaultTemplateLoader(); String template = defaultTemplateLoader.load(new Version(6, 4, 1), "/eventsIndexTemplate"); final JsonElement json = new JsonParser().parse(template); if (!json.isJsonObject()) { throw new IllegalArgumentException("Provided template is not a valid json object"); } JsonObject templateJson = json.getAsJsonObject(); assertNotNull(templateJson); assertFalse(templateJson.toString().isEmpty()); }
Source:
<code>private void registerBeanConfigurerAspectIfNecessary(BeanDefinitionRegistry registry) { <START> if (!registry.containsBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME)) { <END> if (!ClassUtils.isPresent(BEAN_CONFIGURER_ASPECT_CLASS_NAME, getClass().getClassLoader())) { throw new BeanDefinitionStoreException("Could not configure Spring Data JPA auditing-feature because" + " spring-aspects.jar is not on the classpath!\n" + "If you want to use auditing please add spring-aspects.jar to the classpath."); } RootBeanDefinition def = new RootBeanDefinition(); def.setBeanClassName(BEAN_CONFIGURER_ASPECT_CLASS_NAME); def.setFactoryMethodName("aspectOf"); def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME, new BeanComponentDefinition(def, BEAN_CONFIGURER_ASPECT_BEAN_NAME).getBeanDefinition()); } }</code><technical_language>Invert get rid of a level of indentation</technical_language>

Target:
private void registerBeanConfigurerAspectIfNecessary(BeanDefinitionRegistry registry) { if (registry.containsBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME)) { return; } if (!ClassUtils.isPresent(BEAN_CONFIGURER_ASPECT_CLASS_NAME, getClass().getClassLoader())) { throw new BeanDefinitionStoreException("Could not configure Spring Data JPA auditing-feature because" + " spring-aspects.jar is not on the classpath!\n" + "If you want to use auditing please add spring-aspects.jar to the classpath."); } RootBeanDefinition def = new RootBeanDefinition(); def.setBeanClassName(BEAN_CONFIGURER_ASPECT_CLASS_NAME); def.setFactoryMethodName("aspectOf"); def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME, new BeanComponentDefinition(def, BEAN_CONFIGURER_ASPECT_BEAN_NAME).getBeanDefinition()); }
Source:
<code><START> private String getObjectJavaExpression(String exp, Class objectType) throws NoSuchFieldException <END> { StringBuilder sb = new StringBuilder(); String[] split = exp.split("\\."); Class<?> currentClassType = objectType; boolean first = true; for (String field : split) { if (first) { first = false; } else { sb.append("."); } if (field.equals(exprObjPlaceholder)) { sb.append("((").append(objectType.getName().replace("$", "\\$")).append(")").append("(") .append(codeObjPlaceholder).append("))"); currentClassType = objectType; } else { KeyValPair<String, ? extends Class<?>> getter = getGetterForVariable(field, currentClassType); sb.append(getter.getKey()); currentClassType = getter.getValue(); } } return sb.toString(); }</code><technical_language>Is NoSuchFieldException required here? Please check</technical_language>

Target:
private String getObjectJavaExpression(String exp, Class objectType) { StringBuilder sb = new StringBuilder(); String[] split = exp.split("\\."); Class<?> currentClassType = objectType; boolean first = true; for (String field : split) { if (first) { first = false; } else { sb.append("."); } if (field.equals(exprObjPlaceholder)) { sb.append("((").append(objectType.getName().replace("$", "\\$")).append(")").append("(") .append(codeObjPlaceholder).append("))"); currentClassType = objectType; } else { KeyValPair<String, ? extends Class<?>> getter = getGetterForVariable(field, currentClassType); sb.append(getter.getKey()); currentClassType = getter.getValue(); } } return sb.toString(); }
Source:
<code>private String processNodeName(ServiceTreeNode node) { String name = node.getName().substring(0, <START> node.getName().indexOf("Resource")); <END> String[] parts = name.split(CAMEL_CASE_REGEX); name = ""; for (String part : parts) { name += part.toLowerCase() + "-"; } return name.substring(0, name.length() -1); }</code><technical_language>This produce incorrect results if name of service contains "Resource" word, do of those: ExternalComputeResource. want do is remove "Resource" word if is end following: String name = node.getName().replaceAll("Resource$", "");</technical_language>

Target:
private String processNodeName(ServiceTreeNode node) { String[] parts = node.getName().replaceAll("Resource$", "").split(CAMEL_CASE_REGEX); String name = ""; for (String part : parts) { name += part.toLowerCase() + "-"; } return name.substring(0, name.length() -1); }
Source:
<code>private boolean hasContextMultipleReferences(Context context) { int counter = 0; Iterator<Context> iterator = context.getHost().getContexts().iterator(); while (counter <= 1) { <START> if (!iterator.hasNext()) break; <END> if (context.getPath().equals(iterator.next().getPath())) { ++counter; } } return counter > 1; }</code><technical_language>This moved while condition avoid unnecessary break</technical_language>

Target:
private boolean hasContextMultipleReferences(Context context) { int counter = 0; Iterator<Context> iterator = context.getHost().getContexts().iterator(); while (counter <= 1 && iterator.hasNext()) { if (context.getPath().equals(iterator.next().getPath())) { ++counter; } } return counter > 1; }
Source:
<code>public static String buildTravelUrl(String url, String lang) { String title = url.substring(url.indexOf(':') + 1); <START> return "<LINK_1>" + title + "&lang=" + lang; <END> }</code><technical_language>is proper Url.Encode double check @PaulStets encode</technical_language>

Target:
public static String buildTravelUrl(String url, String lang) { String title = url.replace(" ", "_"); try { title = URLEncoder.encode(title, "UTF-8"); } catch (UnsupportedEncodingException e) { System.err.println(e.getMessage()); } return "<LINK_0>" + title + "&lang=" + lang; }
Source:
<code>public SetVdsStatusVDSCommandParameters(Guid vdsId, VDSStatus status) { super(vdsId); _status = status; nonOperationalReason = NonOperationalReason.NONE; <START> logStopSpmFailure = false; <END> }</code><technical_language>unneeded..it false default</technical_language>

Target:
public SetVdsStatusVDSCommandParameters(Guid vdsId, VDSStatus status) { super(vdsId); _status = status; nonOperationalReason = NonOperationalReason.NONE; stopSpmFailureLogged = false; }
Source:
<code>public IAuthorData getEndorserData() { if (!endorsed) { return null; } else { return new IAuthorData() { @Override public String getAuthor() { return endorsedBy; } @Override public String getAuthorLabel() { return endorsedByLabel; } @Override public Date getCreatedAt() { return endorsedAt; } @Override public boolean isAuthorAnonymous() { <START> return DiscussionComment.this.isAuthorAnonymous(); <END> } }; } }</code><technical_language>This check endorsedBy field I guess, is is displayed in endorsed responses</technical_language>

Target:
public IAuthorData getEndorserData() { if (!endorsed) { return null; } else { return new IAuthorData() { @Override public String getAuthor() { return endorsedBy; } @Override public String getAuthorLabel() { return endorsedByLabel; } @Override public Date getCreatedAt() { return endorsedAt; } @Override public boolean isAuthorAnonymous() { return false; } }; } }
Source:
<code>public Models get() { load(); int tries = 0; while (true) { <START> try { <END> return ft.get(); } catch (ExecutionException | InterruptedException e) { tries++; if (tries == 5) { throw new RuntimeException(e); } } } }</code><technical_language>I this loop is doing... need restart task get a result. I fine throw exception retrying anyway. Execution exception runnable throws, I interrupted exception occurs if cancel future task? do that</technical_language>

Target:
public Models get() { load(); try { return mFutureTask.get(); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } }
Source:
<code>private Object findByKey(String key) { Object value = Config.get(request, key); if (value != null) { return value; } <START> value = Config.get(request.getSession(false), key); <END> if (value != null) { return value; } value = Config.get(request.getServletContext(), key); if (value != null) { return value; } return request.getServletContext().getInitParameter(key); }</code><technical_language>@cristianoperez thanks! sounds a default value. a fallback strategy for users for some reason want a new session created. for example: request.getSession(createNewSession()) //... protected boolean createNewSession(){ return false; } do think</technical_language>

Target:
private Object findByKey(String key) { Object value = Config.get(request, key); if (value != null) { return value; } value = Config.get(request.getSession(createNewSession()), key); if (value != null) { return value; } value = Config.get(request.getServletContext(), key); if (value != null) { return value; } return request.getServletContext().getInitParameter(key); }
Source:
<code>public String getName() { <START> return name == null ? simpleAddress.toString() : name.toString(); <END> }</code><technical_language>if address instead of null creating ActiveMQDestination, ensure fields non-null this method return name.toString()</technical_language>

Target:
public String getName() { return name != null ? name : getAddress(); }
Source:
<code>protected int index(int key) { <START> return (entries.length - 1) & (key ^ (key >>> 16)); <END> }</code><technical_language>hash function cache this in methods possible</technical_language>

Target:
protected int index(int key) { return (entries.length - 1) & ((key ^ (key >>> 16)) * MAGIC_HASH_MIXER); }
Source:
<code>private RepositoryCommit getCommit(Repository repository, ObjectId objectId) { RevWalk walk = new RevWalk(repository); try { RevCommit commit = walk.parseCommit(objectId); for (RevCommit parent : commit.getParents()) walk.parseBody(parent); return new RepositoryCommit(repository, commit); } catch (IOException e) { <START> return null; <END> } finally { walk.release(); } }</code><technical_language>This error logged</technical_language>

Target:
private RepositoryCommit getCommit(Repository repository, ObjectId objectId) { RevWalk walk = new RevWalk(repository); try { RevCommit commit = walk.parseCommit(objectId); for (RevCommit parent : commit.getParents()) walk.parseBody(parent); return new RepositoryCommit(repository, commit); } catch (IOException e) { Activator.showError(NLS.bind( UIText.GitProjectPropertyPage_UnableToGetCommit, objectId.name()), e); } finally { walk.release(); } return null; }
Source:
<code><START> public String readMergeCommitMsg() throws IOException { <END> File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG); if (mergeMsgFile.exists()) { int length = (int) mergeMsgFile.length(); char[] messageBuffer = new char[length]; try { FileReader r = new FileReader(mergeMsgFile); r.read(messageBuffer, 0, length); r.close(); return new String(messageBuffer); } catch (FileNotFoundException e) { } } return null; }</code><technical_language>I prefer instead: File msg = new File(gitDir, Constants.MERGE_MSG); try { return new String(IO.readFully(msg)); } catch (FileNotFoundException notFound) { return null; } ensures file fit in memory, ensures read of abort in middle due a short read, ensures file descriptor is closed end. And, FileReader case used, platform default encoding</technical_language>

Target:
public String readMergeCommitMsg() throws IOException { File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG); try { return new String(IO.readFully(mergeMsgFile)); } catch (FileNotFoundException e) { return null; } }
Source:
<code>public void onOpen(WebSocket webSocket, Response response) { try { if (in instanceof PipedInputStream && input != null) { input.connect((PipedInputStream) in); } if (out instanceof PipedOutputStream && output != null) { output.connect((PipedOutputStream) out); } if (err instanceof PipedOutputStream && error != null) { error.connect((PipedOutputStream) err); } if (errChannel instanceof PipedOutputStream && errorChannel != null) { errorChannel.connect((PipedOutputStream) errChannel); } webSocketRef.set(webSocket); if (!executorService.isShutdown()) { executorService.submit(pumper); started.set(true); queue.add(true); } } catch (IOException e) { queue.add(new KubernetesClientException(OperationSupport.createStatus(response))); } catch (RejectedExecutionException rejectedTaskException) { <START> throw new KubernetesClientException("Unable to write to OutputStream since close() has been called.", rejectedTaskException.getCause()); <END> } finally { if (listener != null) { listener.onOpen(response); } } }</code><technical_language>if this Exception reached (at for in message). exectorService.isShutdown() check prevent exception for alleged in message</technical_language>

Target:
public void onOpen(WebSocket webSocket, Response response) { try { if (in instanceof PipedInputStream && input != null) { input.connect((PipedInputStream) in); } if (out instanceof PipedOutputStream && output != null) { output.connect((PipedOutputStream) out); } if (err instanceof PipedOutputStream && error != null) { error.connect((PipedOutputStream) err); } if (errChannel instanceof PipedOutputStream && errorChannel != null) { errorChannel.connect((PipedOutputStream) errChannel); } webSocketRef.set(webSocket); if (!executorService.isShutdown()) { executorService.submit(pumper); started.set(true); queue.add(true); } } catch (IOException e) { queue.add(new KubernetesClientException(OperationSupport.createStatus(response))); } finally { if (listener != null) { listener.onOpen(response); } } }
Source:
<code>public static SrlBankProblem mongoGetBankProblem(final Authenticator authenticator, final DB dbs, final String problemBankId, final String userId) throws AuthenticationException, DatabaseAccessException { final DBRef myDbRef = new DBRef(dbs, PROBLEM_BANK_COLLECTION, createId(problemBankId)); final DBObject mongoBankProblem = myDbRef.fetch(); if (mongoBankProblem == null) { <START> throw new DatabaseAccessException("bank problem can not be found with id " + problemBankId); <END> } final Authentication.AuthType authType = Authentication.AuthType.newBuilder() .setCheckAccess(true) .setCheckingAdmin(true) .build(); final AuthenticationResponder responder = authenticator .checkAuthentication(School.ItemType.BANK_PROBLEM, problemBankId, userId, 0, authType); if (!responder.hasStudentPermission() && responder.isRegistrationRequired()) { throw new AuthenticationException(AuthenticationException.INVALID_PERMISSION); } return extractBankProblem(mongoBankProblem, problemBankId, responder.hasTeacherPermission()); }</code><technical_language>Capitalize letter. Add a colon id, leave space colon</technical_language>

Target:
public static SrlBankProblem mongoGetBankProblem(final Authenticator authenticator, final DB dbs, final String problemBankId, final String userId) throws AuthenticationException, DatabaseAccessException { final DBRef myDbRef = new DBRef(dbs, PROBLEM_BANK_COLLECTION, convertStringToObjectId(problemBankId)); final DBObject mongoBankProblem = myDbRef.fetch(); if (mongoBankProblem == null) { throw new DatabaseAccessException("bank problem can not be found with id: " + problemBankId); } final Authentication.AuthType authType = Authentication.AuthType.newBuilder() .setCheckAccess(true) .setCheckingAdmin(true) .build(); final AuthenticationResponder responder = authenticator .checkAuthentication(School.ItemType.BANK_PROBLEM, problemBankId, userId, 0, authType); if (!responder.hasStudentPermission() && responder.isRegistrationRequired()) { throw new AuthenticationException(AuthenticationException.INVALID_PERMISSION); } return extractBankProblem(mongoBankProblem, problemBankId, responder.hasTeacherPermission()); }
Source:
<code>public KijiFuture<Object> flush() throws IOException { try { final Deferred<Object> deferred = mHBClient.flush(); return AsyncHBaseKijiFuture.create(deferred); } catch (Exception e) { ZooKeeperUtils.wrapAndRethrow(e); <START> final Deferred<Object> error = Deferred.fromError(e); <END> return AsyncHBaseKijiFuture.create(error); } }</code><technical_language>This run for InterruptedException. desired behavior</technical_language>

Target:
public KijiFuture<Object> flush() throws IOException { final Deferred<Object> deferred = mHBClient.flush(); return AsyncHBaseKijiFuture.create(deferred); }
Source:
<code>public String toString() { <START> return "TmfEventMatches [ Number of matches found: " + fMatches.size() + " ]"; END> }</code><technical_language>instead of hard-coding class name (TmfEventMatches), getClass().getSimpleName(). magically work for sub-classes too</technical_language>

Target:
public String toString() { return getClass().getSimpleName() + " [ Number of matches found: " + fMatches.size() + " ]"; }
Source:
<code>public static void setUpClass() { FileUtil.delete("target/data"); EsIndexColumns cols = new EsIndexColumns(def1, def2, def3, def4, def5); esNode = NodeBuilder.nodeBuilder().local(false) .settings(Settings.settingsBuilder().put("path.home", "target/data")) .node(); client = new EsClient("localhost", 9200); index = new EsIndex(client, cols, context, "test", "workspace"); initialIndex(); try { Thread.currentThread().sleep(1000); } catch (Exception e) { <START> } <END> }</code><technical_language>checked exception is InterruptedException if thrown, handled (i.e. interrupted status cleared rethrown)</technical_language>

Target:
public static void setUpClass() throws Exception { FileUtil.delete("target/data"); EsIndexColumns cols = new EsIndexColumns(def1, def2, def3, def4, def5); esNode = NodeBuilder.nodeBuilder().local(false) .settings(Settings.settingsBuilder().put("path.home", "target/data")) .node(); client = new EsClient("localhost", 9200); index = new EsIndex(client, cols, context, "test", "workspace"); initialIndex(); Thread.currentThread().sleep(1000); }
Source:
<code>public void testModifyX() throws Exception { <START> ApplyResult result = init("X"); <END> assertTrue(result.getFormatErrors().isEmpty()); assertTrue(result.getApplyErrors().isEmpty()); checkFile(new File(db.getWorkTree(), "X"), b.getString(0, b.size(), false)); }</code><technical_language>do test this for E, X, Y, Z ? I feel I miss point here..</technical_language>

Target:
public void testModifyX() throws Exception { ApplyResult result = init("X"); assertEquals(1, result.getUpdatedFiles().size()); assertEquals(new File(db.getWorkTree(), "X"), result.getUpdatedFiles() .get(0)); checkFile(new File(db.getWorkTree(), "X"), b.getString(0, b.size(), false)); }
Source:
<code>public static BinaryExpression cmpX(Expression lhv, Expression rhv, boolean reversed) { <START> return (reversed) ? cmpXReversed(lhv, rhv) : cmpX(lhv, rhv); <END> }</code><technical_language>return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv);? eliminate need for new cmpXReversed method</technical_language>

Target:
public static BinaryExpression cmpX(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); }
Source:
<code>private void tallyState(TaskArtifact task) throws OseeCoreException { List<IAtsUser> assignees = task.getStateMgr().getAssignees(); if (assignees.isEmpty()) { assignees = ImplementersColumn.instance.getImplementers(task); } for (IAtsUser user : assignees) { int percentComplete = PercentCompleteTotalUtil.getPercentCompleteTotal(task); if (percentComplete == 100) { <START> task.getCompletedDate(); <END> if (task.getStateMgr().getStateType().isCompletedOrCancelledState()) { metrics.put(user, 100); } else { metrics.put(user, 5); } } else { metrics.put(user, percentComplete); } } }</code><technical_language>Is this - odd call a get method</technical_language>

Target:
private void tallyState(TaskArtifact task) throws OseeCoreException { List<IAtsUser> assignees = task.getStateMgr().getAssignees(); if (assignees.isEmpty()) { assignees = ImplementersColumn.instance.getImplementers(task); } for (IAtsUser user : assignees) { int percentComplete = PercentCompleteTotalUtil.getPercentCompleteTotal(task); if (percentComplete == COMPLETED_CANCELLED_PERCENT) { if (task.getStateMgr().getStateType().isCompletedOrCancelledState()) { metrics.put(user, COMPLETED_CANCELLED_PERCENT); } else { metrics.put(user, IN_WORK_PERCENT); } } else { metrics.put(user, percentComplete); } } }
Source:
<code>private boolean isExceptionToBeRetried( final Class<? extends Throwable> thrown, <START> final Class<? extends Throwable>[] types <END> ) { boolean result = false; for (Class<? extends Throwable> exceptionType : types) { if (exceptionType.isAssignableFrom(thrown)) { result = true; } } return result; }</code><technical_language>This line extra indented</technical_language>

Target:
private boolean isExceptionToBeRetried( final Class<? extends Throwable> thrown, final Class<? extends Throwable>[] types ) { boolean result = false; for (Class<? extends Throwable> type : types) { if (type.isAssignableFrom(thrown)) { result = true; break; } } return result; }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mMapFragment = new GoogleMapFragment(this); mMapFragment.setRetainInstance(true); mLocationTracker = new LocationTracker(getApplicationContext()); mATMListFragment = new ATMListFragment(); Button mapButton = (Button)findViewById(R.id.show_on_map); Button showAllOnMapButton = (Button)findViewById(R.id.show_all_on_map); if (savedInstanceState == null) { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.fragment_container, mATMListFragment); fragmentTransaction.commit(); } setUpActionBar(); setUpDrawer(); mapButton.setOnClickListener(new View.OnClickListener() <START> { <END> @Override public void onClick(View view) { mIsShowAll = true; mDrawerLayout.closeDrawers(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, mMapFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }); showAllOnMapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mDrawerLayout.closeDrawers(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, mMapFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }); }</code><technical_language>avoid code duplication</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mMapFragment = new GoogleMapFragment(this); mMapFragment.setRetainInstance(true); mLocationTracker = new LocationTracker(getApplicationContext()); mATMListFragment = new ATMListFragment(); Button mapButton = (Button)findViewById(R.id.show_on_map); if (savedInstanceState == null) { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.fragment_container, mATMListFragment); fragmentTransaction.commit(); } setUpActionBar(); setUpDrawer(); mapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mDrawerLayout.closeDrawers(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, mMapFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }); }
Source:
<code>public boolean isNetworkDisabledFromOptimizations() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final UsageStatsManagerWrapper usageStatsManagerWrapper = UsageStatsManagerWrapper.getInstance(); if (usageStatsManagerWrapper.isAppInactive(mConnectionContext)) { <START> Logger.w(TAG, "Company Portal is Inactive. Network is disabled.", "", ADALError.NO_NETWORK_CONNECTION_POWER_OPTIMIZATION); <END> return true; } final PowerManagerWrapper powerManagerWrapper = PowerManagerWrapper.getInstance(); if (powerManagerWrapper.isDeviceIdleMode(mConnectionContext) && !powerManagerWrapper.isIgnoringBatteryOptimizations(mConnectionContext)) { Logger.w(TAG, "Device is Dozing. Network is disabled.", "", ADALError.NO_NETWORK_CONNECTION_POWER_OPTIMIZATION); return true; } } return false; }</code><technical_language>log message is "company portal is inactive"</technical_language>

Target:
public boolean isNetworkDisabledFromOptimizations() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final UsageStatsManagerWrapper usageStatsManagerWrapper = UsageStatsManagerWrapper.getInstance(); if (usageStatsManagerWrapper.isAppInactive(mConnectionContext)) { Logger.w(TAG, "Client app is inactive. Network is disabled.", "", ADALError.NO_NETWORK_CONNECTION_POWER_OPTIMIZATION); return true; } final PowerManagerWrapper powerManagerWrapper = PowerManagerWrapper.getInstance(); if (powerManagerWrapper.isDeviceIdleMode(mConnectionContext) && !powerManagerWrapper.isIgnoringBatteryOptimizations(mConnectionContext)) { Logger.w(TAG, "Device is dozing. Network is disabled.", "", ADALError.NO_NETWORK_CONNECTION_POWER_OPTIMIZATION); return true; } } return false; }
Source:
<code>public HBMessage send(HBMessage m) throws PacemakerConnectionException, InterruptedException { LOG.debug("Sending pacemaker message to {}: {}", host, m); int next = availableMessageSlots.take(); synchronized (m) { m.set_message_id(next); messages[next] = m; LOG.debug("Put message in slot: for {}", Integer.toString(next), host); int retry = maxRetries; while (true) { try { waitUntilReady(); Channel channel = channelRef.get(); if (channel != null) { channel.writeAndFlush(m, channel.voidPromise()); m.wait(1000); } if (messages[next] != m && messages[next] != null) { HBMessage ret = messages[next]; messages[next] = null; LOG.debug("Got Response: {}", ret); return ret; } } catch (PacemakerConnectionException e) { if (retry <= 0) { throw e; } <START> LOG.error("Error attempting to write to a channel to host " + host + " - " + e.getMessage()); <END> } if (retry <= 0) { throw new PacemakerConnectionException("couldn't get response after " + maxRetries + " attempts."); } retry--; LOG.warn("Not getting response or getting null response. Making more attempts for {}.", retry, host); } } }</code><technical_language>{}</technical_language>

Target:
public HBMessage send(HBMessage m) throws PacemakerConnectionException, InterruptedException { LOG.debug("Sending pacemaker message to {}: {}", host, m); int next = availableMessageSlots.take(); synchronized (m) { m.set_message_id(next); messages[next] = m; LOG.debug("Put message in slot: for {}", Integer.toString(next), host); int retry = maxRetries; while (true) { try { waitUntilReady(); Channel channel = channelRef.get(); if (channel != null) { channel.writeAndFlush(m, channel.voidPromise()); m.wait(1000); } if (messages[next] != m && messages[next] != null) { HBMessage ret = messages[next]; messages[next] = null; LOG.debug("Got Response: {}", ret); return ret; } } catch (PacemakerConnectionException e) { if (retry <= 0) { throw e; } LOG.error("Error attempting to write to a channel to host - {}", host, e.getMessage()); } if (retry <= 0) { throw new PacemakerConnectionException("couldn't get response after " + maxRetries + " attempts."); } retry--; LOG.warn("Not getting response or getting null response. Making more attempts for {}.", retry, host); } } }
Source:
<code><START> public WeldBootstrap getBootstrap() { <END> return bootstrap; }</code><technical_language>Is this needed</technical_language>

Target:
WeldBootstrap getBootstrap() { return bootstrap; }
Source:
<code>public DaemonOperationResult execute() throws OperationException { logger.log(Level.INFO, "Starting daemon operation with action " + options.getAction() + " ..."); switch (options.getAction()) { case LIST: return executeList(); case ADD: <START> try { <END> return executeAdd(); } catch (ConfigException | IOException e) { throw new OperationException(e); } case REMOVE: try { return executeRemove(); } catch (ConfigException e) { throw new OperationException(e); } case RUN: try { return executeRun(); } catch (ServiceAlreadyStartedException | IOException | ConfigException e) { throw new OperationException(e); } default: throw new IllegalArgumentException("Unknown action: " + options.getAction()); } }</code><technical_language>try/catch blocks in switch/case odd. throw OperationException in execute*() methods</technical_language>

Target:
public DaemonOperationResult execute() throws OperationException { logger.log(Level.INFO, "Starting daemon operation with action " + options.getAction() + " ..."); switch (options.getAction()) { case LIST: return executeList(); case ADD: return executeAdd(); case REMOVE: return executeRemove(); case RUN: return executeRun(); default: throw new IllegalArgumentException("Unknown action: " + options.getAction()); } }