auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Iterator<Pair<K, V>> iterator() { return new Iterator<Pair<K, V>>() { @SuppressWarnings("unchecked") private final HashTable<K, V>[] stack = new HashTable[Fork.this.length]; private Maybe<Iterator<Pair<K, V>>> currentIterator = Maybe.empty(); int i = 0; { this.stack[this.i++] = Fork.this; } private void updateState() { if (currentIterator.isJust() && currentIterator.fromJust().hasNext()) { return; } else { currentIterator = Maybe.empty(); } while (this.i > 0 && currentIterator.isNothing()) { HashTable<K, V> curr = this.stack[--this.i]; if (curr instanceof Fork) { Fork<K, V> fork = (Fork<K, V>) curr; for (HashTable<K, V> child : fork.children) { <START> this.stack[this.i++] = child; <END> } } else if (curr instanceof Leaf) { currentIterator = Maybe.of(((Leaf<K, V>) curr).dataList.iterator()); if (currentIterator.fromJust().hasNext()) { return; } else { currentIterator = Maybe.empty(); } } } } @Override public boolean hasNext() { updateState(); return currentIterator.isJust() && currentIterator.fromJust().hasNext(); } @Override public Pair<K, V> next() { updateState(); if (currentIterator.isJust() && currentIterator.fromJust().hasNext()) { return currentIterator.fromJust().next(); } throw new NoSuchElementException(); } }; }</code><technical_language>want add non-null children, I expect</technical_language>

Target:
public Iterator<Pair<K, V>> iterator() { return new Iterator<Pair<K, V>>() { @SuppressWarnings("unchecked") private final HashTable<K, V>[] stack = new HashTable[Fork.this.length]; private Iterator<Pair<K, V>> currentIterator = null; int i = 0; { this.stack[this.i++] = Fork.this; } private void updateState() { if (currentIterator != null && currentIterator.hasNext()) { return; } else { currentIterator = null; } while (this.i > 0) { this.i--; HashTable<K, V> curr = this.stack[this.i]; if (curr instanceof Fork) { Fork<K, V> fork = (Fork<K, V>) curr; for (HashTable<K, V> child : fork.children) { if (child != null) { this.stack[this.i] = child; this.i++; } } } else if (curr instanceof Leaf) { currentIterator = ((Leaf<K, V>) curr).dataList.iterator(); if (currentIterator.hasNext()) { return; } else { currentIterator = null; } } } } @Override public boolean hasNext() { updateState(); return currentIterator != null; } @Override public Pair<K, V> next() { updateState(); if (currentIterator == null) { throw new NoSuchElementException(); } return currentIterator.next(); } }; }
Source:
<code>public static <T> T notNull(T value, String message) { if (value == null) { <START> throw new NullPointerException(String.valueOf(message)); <END> } return value; }</code><technical_language>I suggest passing message String.valueOf()</technical_language>

Target:
public static <T> T notNull(T value, String message) { if (value == null) { throw new NullPointerException(message); } return value; }
Source:
<code>public void testListSecurityGroupsForNode() { HttpRequest serverReq = HttpRequest.builder().method("GET").endpoint( URI.create("<LINK_1>")) .headers( ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); HttpResponse serverResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/server_with_security_groups_extension.json")).build(); HttpRequest list = HttpRequest.builder().method("GET").endpoint( URI.create("<LINK_0>")).headers( ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_list.json")).build(); Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder(); requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess); requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse); requestResponseMap.put(serverReq, serverResponse); requestResponseMap.put(list, listResponse).build(); SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get(); Set<SecurityGroup> groups = extension.listSecurityGroupsForNode(zone + "/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb"); <START> assertEquals(1, groups.size()); <END> }</code><technical_language>assertEquals(boolean actual, boolean expected)</technical_language>

Target:
public void testListSecurityGroupsForNode() { HttpRequest serverReq = HttpRequest.builder().method("GET").endpoint( URI.create("<LINK_1>")) .headers( ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); HttpResponse serverResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/server_with_security_groups_extension.json")).build(); HttpRequest list = HttpRequest.builder().method("GET").endpoint( URI.create("<LINK_0>")).headers( ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_list.json")).build(); Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder(); requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess); requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse); requestResponseMap.put(serverReq, serverResponse); requestResponseMap.put(list, listResponse).build(); SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get(); Set<SecurityGroup> groups = extension.listSecurityGroupsForNode(zone + "/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb"); assertEquals(groups.size(), 1); }
Source:
<code>private ModelAndView setupForm(SequencerPartitionContainer container, ModelMap model) throws IOException { <START> model.put("formObj", container); <END> model.put("container", container); model.put("containerPartitions", container.getPartitions().stream().map(Dtos::asDto).collect(Collectors.toList())); model.put("containerRuns", runService.listByContainerId(container.getId()).stream().map(Dtos::asDto).collect(Collectors.toList())); return new ModelAndView("/pages/editSequencerPartitionContainer.jsp", model); }</code><technical_language>I this is for container is included right this</technical_language>

Target:
private ModelAndView setupForm(SequencerPartitionContainer container, ModelMap model) throws IOException { model.put("container", container); model.put("containerPartitions", container.getPartitions().stream().map(Dtos::asDto).collect(Collectors.toList())); model.put("containerRuns", runService.listByContainerId(container.getId()).stream().map(Dtos::asDto).collect(Collectors.toList())); return new ModelAndView("/pages/editSequencerPartitionContainer.jsp", model); }
Source:
<code>private void writeSystemInfo() { if (vm.getClusterArch().getFamily() != ArchitectureType.x86) { return; } final String product = Config.getValue(ConfigValues.OriginType); final String manufacturer = OriginType.valueOf(product) == OriginType.OVIRT ? "oVirt" : "Red Hat"; final boolean needsBaseBoard = OriginType.valueOf(product) == OriginType.RHEV; final String productName = OriginType.valueOf(product) == OriginType.OVIRT ? "oVirt" : "RHV"; writer.writeStartElement("sysinfo"); writer.writeAttributeString("type", "smbios"); writer.writeStartElement("system"); writeEntryElement("manufacturer", manufacturer); writeEntryElement("product", productName); writeEntryElement("version", vm.getClusterCompatibilityVersion().toString()); writeEntryElement("family", "Red Hat Enterprise Linux"); writeEntryElement("sku", Config.getValue(ConfigValues.SkuToAVLevel, vm.getCompatibilityVersion().toString())); writeEntryElement("serial", "HOST-SERIAL:"); writeEntryElement("uuid", vm.getId().toString()); writer.writeEndElement(); if (needsBaseBoard) { writer.writeStartElement("baseBoard"); writeEntryElement("manufacturer", "Red Hat"); writeEntryElement("product", "RHEL-AV"); writer.writeEndElement(); } writer.writeEndElement(); }</code><technical_language>I add "can set in vdc_options" remove upstream</technical_language>

Target:
private void writeSystemInfo() { if (vm.getClusterArch().getFamily() != ArchitectureType.x86) { return; } final String product = Config.getValue(ConfigValues.OriginType); final String manufacturer = OriginType.valueOf(product) == OriginType.OVIRT ? "oVirt" : "Red Hat"; final String productName = OriginType.valueOf(product) == OriginType.OVIRT ? "oVirt" : "RHV"; writer.writeStartElement("sysinfo"); writer.writeAttributeString("type", "smbios"); writer.writeStartElement("system"); writeEntryElement("manufacturer", manufacturer); writeEntryElement("product", productName); writeEntryElement("version", vm.getClusterCompatibilityVersion().toString()); writeEntryElement("family", "Red Hat Enterprise Linux"); if (Config.valueExists(ConfigValues.SkuToAVLevel, vm.getCompatibilityVersion().toString())) { writeEntryElement("sku", Config.getValue(ConfigValues.SkuToAVLevel, vm.getCompatibilityVersion().toString())); } writeEntryElement("serial", "HOST-SERIAL:"); writeEntryElement("uuid", vm.getId().toString()); writer.writeEndElement(); if (Config.getValue(ConfigValues.IncludeBaseboardSysinfo)) { writer.writeStartElement("baseBoard"); writeEntryElement("manufacturer", "Red Hat"); writeEntryElement("product", "RHEL-AV"); writer.writeEndElement(); } writer.writeEndElement(); }
Source:
<code>@Override public void onMatch(RelOptRuleCall call) { final Join join = call.rel(0); final RexBuilder rexBuilder = join.getCluster().getRexBuilder(); <START> RexSimplify rexSimplify = <END> new RexSimplify(rexBuilder, RelOptPredicateList.EMPTY, EXECUTOR); RexNode condition = rexSimplify.eliminateCommonExprInCondition(join.getCondition()); final List<RexNode> expList = Lists.newArrayList(condition); final int fieldCount = join.getLeft().getRowType().getFieldCount(); final RelMetadataQuery mq = call.getMetadataQuery(); final RelOptPredicateList leftPredicates = mq.getPulledUpPredicates(join.getLeft()); final RelOptPredicateList rightPredicates = mq.getPulledUpPredicates(join.getRight()); final RelOptPredicateList predicates = leftPredicates.union(rexBuilder, rightPredicates.shift(rexBuilder, fieldCount)); if (!reduceExpressions(join, expList, predicates, true, config.matchNullability())) { return; } call.transformTo( join.copy( join.getTraitSet(), expList.get(0), join.getLeft(), join.getRight(), join.getJoinType(), join.isSemiJoinDone())); call.getPlanner().prune(join); }</code><technical_language>For consistency rest of code in method, I guess if rexSimplify condition declared final</technical_language>

Target:
@Override public void onMatch(RelOptRuleCall call) { final Join join = call.rel(0); final RexBuilder rexBuilder = join.getCluster().getRexBuilder(); final RexSimplify rexSimplify = new RexSimplify(rexBuilder, RelOptPredicateList.EMPTY, EXECUTOR); final RexNode condition = rexSimplify.eliminateCommonExprInCondition(join.getCondition()); final List<RexNode> expList = Lists.newArrayList(condition); final int fieldCount = join.getLeft().getRowType().getFieldCount(); final RelMetadataQuery mq = call.getMetadataQuery(); final RelOptPredicateList leftPredicates = mq.getPulledUpPredicates(join.getLeft()); final RelOptPredicateList rightPredicates = mq.getPulledUpPredicates(join.getRight()); final RelOptPredicateList predicates = leftPredicates.union(rexBuilder, rightPredicates.shift(rexBuilder, fieldCount)); if (!reduceExpressions(join, expList, predicates, true, config.matchNullability())) { return; } call.transformTo( join.copy( join.getTraitSet(), expList.get(0), join.getLeft(), join.getRight(), join.getJoinType(), join.isSemiJoinDone())); call.getPlanner().prune(join); }
Source:
<code>public void setUp() throws Exception { <START> File rootDir = Files.createTempDir(); <END> rootDir.deleteOnExit(); fileSystemJarCache = new FileSystemJarCache(rootDir, true); expectedChecksum = ChecksumTest.createdExpectedChecksum( Hashing.sha256().hashBytes(CONTENTS.getBytes(Charset.forName("UTF-8")))); }</code><technical_language>TemporaryFolder rule</technical_language>

Target:
public void setUp() throws Exception { fileSystemJarCache = new FileSystemJarCache(tmp.getRoot(), true); expectedChecksum = ChecksumTest.createdExpectedChecksum( Hashing.sha256().hashBytes(CONTENTS.getBytes(Charset.forName("UTF-8")))); }
Source:
<code>public Query apply(Function input, LuceneQueryBuilder.Context context) { RefAndLiteral refAndLiteral = RefAndLiteral.of(input); if (refAndLiteral == null) { return null; } String colName = refAndLiteral.reference().column().fqn(); MappedFieldType fieldType = context.getFieldTypeOrNull(colName); if (fieldType == null) { return Queries.newMatchNoDocsQuery("column does not exist in this index"); } String cidr = (String) refAndLiteral.literal().value(); Tuple<InetAddress, InetAddress> cidrRange = CIDROperator.extractRange(cidr); <START> return fieldType.rangeQuery(cidrRange.v1(), cidrRange.v2(), true, <END> false, null, null, context.queryShardContext); }</code><technical_language>In IpFieldMapper term query logic: if (term.contains("/")) { final Tuple<InetAddress, Integer> cidr = InetAddresses.parseCidr(term); return InetAddressPoint.newPrefixQuery(name(), cidr.v1(), cidr.v2()); } instead well? remove need for CIDROperator.extractRange(cidr); get rid of IpRangeConsumer abstraction CIDROperator</technical_language>

Target:
public Query apply(Function input, LuceneQueryBuilder.Context context) { RefAndLiteral refAndLiteral = RefAndLiteral.of(input); if (refAndLiteral == null) { return null; } String colName = refAndLiteral.reference().column().fqn(); MappedFieldType fieldType = context.getFieldTypeOrNull(colName); if (fieldType == null) { return Queries.newMatchNoDocsQuery("column does not exist in this index"); } String cidrStr = (String) refAndLiteral.literal().value(); Tuple<InetAddress, Integer> cidr = InetAddresses.parseCidr(cidrStr); return InetAddressPoint.newPrefixQuery(fieldType.name(), cidr.v1(), cidr.v2()); }
Source:
<code>public void clearID() { idSupplier = null; <START> nodeMap.clear(); END> nodeMap = null; }</code><technical_language>suggestion if (nodeMap != null) { nodeMap.clear(); nodeMap = null; }</technical_language>

Target:
public void clearID() { idSupplier = null; if (nodeMap != null) { nodeMap.clear(); nodeMap = null; } }
Source:
<code>private Object deserializeItem(Object item) { try { Class klass = YoutubeEventClassifier.detectClass((String) item); <START> System.out.println(klass.getName()); <END> if (klass.equals(Video.class)) { item = mapper.readValue((String) item, Video.class); } else if(klass.equals(Channel.class)) { item = mapper.readValue((String) item, Channel.class); } } catch (Exception e) { LOGGER.error("Exception while trying to deserializeItem: {}", e); } return item; }</code><technical_language>If this, change a log statement</technical_language>

Target:
private Object deserializeItem(Object item) { try { Class klass = YoutubeEventClassifier.detectClass((String) item); if (klass.equals(Video.class)) { item = mapper.readValue((String) item, Video.class); } else if(klass.equals(Channel.class)) { item = mapper.readValue((String) item, Channel.class); } } catch (Exception e) { LOGGER.error("Exception while trying to deserializeItem: {}", e); } return item; }
Source:
<code>@Override public String url(HttpRequest request) { <START> StringBuffer url = new StringBuffer("http://"); <END> String host = request.headers().get("HOST"); if (host != null) url.append(host); url.append(request.uri()); return url.toString(); }</code><technical_language>want StringBuilder</technical_language>

Target:
@Override public String url(HttpRequest request) { String host = requestHeader(request, "Host"); if (host == null) return null; return "http://" + host + request.uri(); }
Source:
<code>public AdobePDFSchemaImpl(AdobePDFSchema schema, Metadata metadata) { <START> this.schema = schema; <END> this.metadata = metadata; }</code><technical_language>check</technical_language>

Target:
public AdobePDFSchemaImpl(AdobePDFSchema schema, Metadata metadata) { if (schema == null) { throw new IllegalArgumentException("AdobePdf schema representation can not be null"); } if (metadata == null) { throw new IllegalArgumentException("Metadata representation can not be null"); } this.schema = schema; this.metadata = metadata; }
Source:
<code>public AnAction[] getChildren(@Nullable AnActionEvent event) { ActionManager actionManager = ActionManager.getInstance(); DefaultActionGroup actionGroup = (DefaultActionGroup) actionManager.getAction(PantsConstants.ACTION_COMPILE_GROUP_ID); actionGroup.remove(actionManager.getAction(IdeActions.ACTION_MAKE_MODULE)); actionGroup.remove(actionManager.getAction(IdeActions.ACTION_COMPILE)); final AnAction[] emptyAction = new AnAction[0]; if (event == null) { return emptyAction; } Project project = event.getProject(); Optional<VirtualFile> eventFile = IPantsGetTargets.getFileForEvent(event); if (project == null || !eventFile.isPresent()) { return emptyAction; } VirtualFile file = eventFile.get(); Module module = ModuleUtil.findModuleForFile(file, project); if (module == null) { return emptyAction; } List<String> targetAddresses = PantsUtil.getNonGenTargetAddresses(module); if (targetAddresses.isEmpty()) { return emptyAction; } List<AnAction> actions = new LinkedList<>(); if (targetAddresses.size() > 1) { actions.add(new PantsCompileAllTargetsInModuleAction(module)); } <START> targetAddresses.forEach(target -> actions.add(new PantsCompileTargetAction(target))); <END> return actions.toArray(emptyAction); }</code><technical_language>Is this change necessary? benefit provide</technical_language>

Target:
public AnAction[] getChildren(@Nullable AnActionEvent event) { ActionManager actionManager = ActionManager.getInstance(); DefaultActionGroup actionGroup = (DefaultActionGroup) actionManager.getAction(PantsConstants.ACTION_COMPILE_GROUP_ID); actionGroup.remove(actionManager.getAction(IdeActions.ACTION_MAKE_MODULE)); actionGroup.remove(actionManager.getAction(IdeActions.ACTION_COMPILE)); final AnAction[] emptyAction = new AnAction[0]; if (event == null) { return emptyAction; } Project project = event.getProject(); Optional<VirtualFile> eventFile = PantsUtil.getFileForEvent(event); if (project == null || !eventFile.isPresent()) { return emptyAction; } VirtualFile file = eventFile.get(); List<AnAction> actions = new LinkedList<>(); Module module = ModuleUtil.findModuleForFile(file, project); if (module == null) { return emptyAction; } List<String> targetAddresses = PantsUtil.getNonGenTargetAddresses(module); if (targetAddresses.isEmpty()) { return emptyAction; } actions.add(new PantsLintTargetAction(targetAddresses)); if (targetAddresses.size() > 1) { actions.add(new PantsCompileAllTargetsInModuleAction(Optional.of(module))); } targetAddresses.forEach(target -> actions.add(new PantsCompileTargetAction(target))); return actions.toArray(emptyAction); }
Source:
<code>public void update(Object[] srcRow, Object[] destRow) { Number value = (Number) srcRow[pos]; if (value != null) { Number sum = (Number) destRow[pos]; if (sum == null) { destRow[pos] = value; } else { <START> destRow[pos] = sum.intValue() + value.intValue(); END> } } }</code><technical_language>I a long double respectively</technical_language>

Target:
public void update(Object[] srcRow, Object[] destRow) { Number value = (Number) srcRow[pos]; if (value != null) { Number sum = (Number) destRow[pos]; if (sum == null) { destRow[pos] = value; } else { destRow[pos] = add(value, sum); } } }
Source:
<code>final protected void interrupted() { onInterrupted(); <START> if (previous != null && (!previous.isScheduled())) { <END> previous.schedule(); } }</code><technical_language>remove extra parentheses</technical_language>

Target:
protected final void interrupted() { onInterrupted(); if (previous != null && !previous.isScheduled()) { previous.schedule(); } }
Source:
<code>protected void doPush(final ProgressMonitor monitor, final Map<String, RemoteRefUpdate> refUpdates) throws TransportException { final InputStream httpIn; final OutputStream httpOut; try { final URL url = new URL(baseUrl, "git-receive-pack"); final Proxy proxy = HttpSupport.proxyFor(proxySelector, url); final HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(proxy); <START> conn.setRequestMethod("POST"); <END> conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setChunkedStreamingMode(0); conn.setRequestProperty("Content-Type", REQ_TYPE); httpOut = new BufferedOutputStream(conn.getOutputStream()); httpIn = new HttpInputStream(conn, httpOut, RSP_TYPE); } catch (IOException e) { throw new TransportException(uri, "Cannot begin HTTP push", e); } init(new BufferedInputStream(httpIn), httpOut); super.doPush(monitor, refUpdates); }</code><technical_language>a constants file for representing e.g. HTTP_METHOD_POST HTTP_HEADER_CONTENT_TYPE</technical_language>

Target:
protected void doPush(final ProgressMonitor monitor, final Map<String, RemoteRefUpdate> refUpdates) throws TransportException { final InputStream httpIn; final OutputStream httpOut; try { final URL url = new URL(baseUrl, "git-receive-pack"); final Proxy proxy = HttpSupport.proxyFor(proxySelector, url); final HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(proxy); conn.setRequestMethod(HttpSupport.METHOD_POST); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setChunkedStreamingMode(0); conn.setRequestProperty(HttpSupport.HDR_CONTENT_TYPE, REQ_TYPE); httpOut = new BufferedOutputStream(conn.getOutputStream()); httpIn = new HttpInputStream(conn, httpOut, RSP_TYPE); } catch (IOException e) { throw new TransportException(uri, "Cannot begin HTTP push", e); } init(new BufferedInputStream(httpIn), httpOut); super.doPush(monitor, refUpdates); }
Source:
<code>public void initializeWhitelist( final MavenRepository mavenRepository ) { getLogger().debug( "Initializing white-list of newly added {}", <START> RepositoryStringUtils.getHumanizedNameString( mavenRepository ) ); <END> try { unpublish( mavenRepository ); updateWhitelist( mavenRepository ); getLogger().info( "Initializing non existing white-list of newly added {}", RepositoryStringUtils.getHumanizedNameString( mavenRepository ) ); } catch ( Exception e ) { getLogger().warn( "Problem during white-list initialisation of newly added {}", RepositoryStringUtils.getHumanizedNameString( mavenRepository ), e ); try { unpublish( mavenRepository ); } catch ( IOException ioe ) { } } }</code><technical_language>Curious, default toString() of objects rendering "humanized" forms? This "humanization" of str repr done allow for slf4j optimization avoid string concat for logs this level is enabled. stuff this guarded. I recommend consider changing toString() render is for logging, in this case {{getHumanizedNameString()}} is avoid copying this code place</technical_language>

Target:
public void initializeWhitelist( final MavenRepository mavenRepository ) { getLogger().debug( "Initializing white-list of newly added {}", mavenRepository ); try { unpublish( mavenRepository ); updateWhitelist( mavenRepository ); getLogger().info( "Initializing non-existing white-list of newly added {}", RepositoryStringUtils.getHumanizedNameString( mavenRepository ) ); } catch ( Exception e ) { getLogger().warn( "Problem during white-list initialisation of newly added {}", RepositoryStringUtils.getHumanizedNameString( mavenRepository ), e ); try { unpublish( mavenRepository ); } catch ( IOException ioe ) { } } }
Source:
<code>public boolean add(final String key, final int exp, final byte[] o) throws IOException { if (_log.isDebugEnabled()) _log.debug(String.format("Adding key to Redis (key=%s, exp=%d, %d bytes)", key, exp, o.length)); return (new JedisCommandRunner<Boolean>() { <START> private boolean _setCompleted; <END> @Override protected Boolean execute(BinaryJedis jedis) { byte[] kb = keyBytes(key); if (_setCompleted || jedis.setnx(kb, o) == 1) { _setCompleted = true; if (exp == 0) return true; else return jedis.expire(kb, convertExp(exp)) == 1; } else { return false; } } }).run(); }</code><technical_language>this volatile? is guaranteed this is run thread if connection failed</technical_language>

Target:
public Future<Boolean> add(final String key, final int exp, final byte[] o) { if (_log.isDebugEnabled()) _log.debug(String.format("Adding key to Redis (key=%s, exp=%s, o=%s)", key, exp, o.getClass().getName())); return _executor.submit(new RedisCommandCallable<Boolean>() { private volatile boolean _setCompleted; @Override protected Boolean execute(BinaryJedis jedis) throws Exception { byte[] kb = keyBytes(key); if (_setCompleted || jedis.setnx(kb, o) == 1) { _setCompleted = true; if (exp == 0) return true; else return jedis.expire(kb, convertExp(exp)) == 1; } else { return false; } } }); }
Source:
<code>public void onPropertyChange(EnvironmentChangeEvent event) { if (!customHttpClient) { boolean createNewClient = false; for (String key : event.getKeys()) { if (key.startsWith("zuul.host.")) { createNewClient = true; break; } } if (createNewClient) { try { SimpleHostRoutingFilter.this.httpClient.close(); } catch (IOException ex) { log.error("error closing client", ex); } <START> SimpleHostRoutingFilter.this.connectionManager.shutdown(); <END> SimpleHostRoutingFilter.this.connectionManager = newConnectionManager(); SimpleHostRoutingFilter.this.httpClient = newClient(); } } }</code><technical_language>This move in try catch in own</technical_language>

Target:
public void onPropertyChange(EnvironmentChangeEvent event) { if (!customHttpClient) { boolean createNewClient = false; for (String key : event.getKeys()) { if (key.startsWith("zuul.host.")) { createNewClient = true; break; } } if (createNewClient) { try { this.httpClient.close(); } catch (IOException ex) { log.error("error closing client", ex); } try { this.connectionManager.shutdown(); } catch (RuntimeException ex) { log.error("error shutting down connection manager", ex); } this.connectionManager = newConnectionManager(); this.httpClient = newClient(); } } }
Source:
<code>public boolean isPostFollowed() { <START> this.waitForPageLoad(); <END> return this.getPost().findNewestPost().isFollowed(); }</code><technical_language>is this. necessary</technical_language>

Target:
public boolean isPostFollowed() { waitForPageLoad(); return getPost().findNewestPost().isFollowed(); }
Source:
<code>private void currentBuildResultFailure(AbstractBuild<?, ?> build, BuildListener listener, Result previousBuildResult, String filename, EnvVars vars) throws InterruptedException, IOException { if (previousBuildResult == Result.FAILURE) { String comment = String.format("Build is still failing.\nFailed run: %s", getBuildDetailsString(vars)); String issueId = getIssue(filename); if (issueId != null) { try { Status status = getStatus(build, issueId); <START> if (status.getName().equals("Closed") || status.getName().equals("Done")) { <END> listener.getLogger().println("The previous build also failed but the issue is closed"); deleteFile(filename); Issue issue = createJiraIssue(build, filename); LOG.info(String.format("[%s] created.", issue.getKey())); }else { addComment(build, issueId, comment); LOG.info(String.format("[%s] The previous build also failed, comment added.", issueId)); } } catch (IOException e) { LOG.warning(String.format("[%s] - error processing JIRA change: %s", issueId, e.getMessage())); } } } if (previousBuildResult == Result.SUCCESS || previousBuildResult == Result.ABORTED) { try { Issue issue = createJiraIssue(build, filename); listener.getLogger().println("Build failed, created JIRA issue " + issue.getKey()); } catch (IOException e) { listener.error("Error creating JIRA issue : " + e.getMessage()); LOG.warning("Error creating JIRA issue\n" + e.getMessage()); } } }</code><technical_language>statuses pre-defined constants, store in Enum object</technical_language>

Target:
private void currentBuildResultFailure(AbstractBuild<?, ?> build, BuildListener listener, Result previousBuildResult, String filename, EnvVars vars) throws InterruptedException, IOException { if (previousBuildResult == Result.FAILURE) { String comment = String.format("Build is still failing.\nFailed run: %s", getBuildDetailsString(vars)); String issueId = getIssue(filename); if (issueId != null) { try { Status status = getStatus(build, issueId); if ( status.getName().equalsIgnoreCase(finishedStatuses.Closed.toString()) || status.getName().equalsIgnoreCase(finishedStatuses.Done.toString()) ) { listener.getLogger().println("The previous build also failed but the issue is closed"); deleteFile(filename); Issue issue = createJiraIssue(build, filename); LOG.info(String.format("[%s] created.", issue.getKey())); }else { addComment(build, issueId, comment); LOG.info(String.format("[%s] The previous build also failed, comment added.", issueId)); } } catch (IOException e) { LOG.warning(String.format("[%s] - error processing JIRA change: %s", issueId, e.getMessage())); } } } if (previousBuildResult == Result.SUCCESS || previousBuildResult == Result.ABORTED) { try { Issue issue = createJiraIssue(build, filename); listener.getLogger().println("Build failed, created JIRA issue " + issue.getKey()); } catch (IOException e) { listener.error("Error creating JIRA issue : " + e.getMessage()); LOG.warning("Error creating JIRA issue\n" + e.getMessage()); } } }
Source:
<code>public void realmResults_emittedChangesetOnUpdate() { RealmResults<AllTypes> results = realm.where(AllTypes.class).findAll(); subscription = results.asChangesetObservable().subscribe(change -> { RealmResults<AllTypes> rxResults = change.getCollection(); assertTrue(rxResults.isFrozen()); if (rxResults.isEmpty()) { realm.executeTransaction(r -> r.createObject(AllTypes.class)); } else if (rxResults.size() == 1) { <START> assertEquals(1, change.getChangeset().getInsertions().length); <END> looperThread.testComplete(); } }); }</code><technical_language>Do test showing other updates (modifications, deletes ...)</technical_language>

Target:
public void realmResults_emittedChangesetOnUpdate() { RealmResults<AllTypes> results = realm.where(AllTypes.class).findAll(); subscription = results.asChangesetObservable().subscribe(change -> { RealmResults<AllTypes> rxResults = change.getCollection(); assertTrue(rxResults.isFrozen()); if (rxResults.isEmpty()) { realm.executeTransaction(r -> r.createObject(AllTypes.class)); } else if (rxResults.size() == 1) { assertEquals(1, change.getChangeset().getInsertions().length); disposeSuccessfulTest(realm); } }); }
Source:
<code>private Optional<TreeItem<GroupNodeViewModel>> getTreeItemByValue(TreeItem<GroupNodeViewModel> root, GroupNodeViewModel value) { if (root.getValue().equals(value)) { return Optional.of(root); } Optional<TreeItem<GroupNodeViewModel>> node = Optional.empty(); <START> for (int i = 0; i < root.getChildren().size() && node.isEmpty(); i++) { <END> node = getTreeItemByValue(root.getChildren().get(i), value); } return node; }</code><technical_language>please convert this a normal foreach loop. I guess works: java for (TreeItem<GroupNodeViewModel> child: root.getChildren()) { Optional<TreeItem<GroupNodeViewModel>> node = getTreeItemByValue(child, value); if (node.isPresent()) return node; } return Optional.empty();</technical_language>

Target:
private Optional<TreeItem<GroupNodeViewModel>> getTreeItemByValue(TreeItem<GroupNodeViewModel> root, GroupNodeViewModel value) { if (root.getValue().equals(value)) { return Optional.of(root); } Optional<TreeItem<GroupNodeViewModel>> node = Optional.empty(); for (TreeItem<GroupNodeViewModel> child : root.getChildren()) { node = getTreeItemByValue(child, value); if (node.isPresent()) { break; } } return node; }
Source:
<code>private static StoreQueryRuntime constructStoreQueryRuntime(Table table, StoreQuery storeQuery, SiddhiAppContext siddhiAppContext, Map<String, Table> tableMap, Map<String, Window> windowMap, String queryName, int metaPosition, Expression onCondition, MetaStreamEvent metaStreamEvent, List<VariableExpressionExecutor> variableExpressionExecutors, LockWrapper lockWrapper) { if (table instanceof QueryableProcessor && storeQuery.getType() == StoreQuery.StoreQueryType.FIND) { try { return constructOptimizedStoreQueryRuntime(table, storeQuery, siddhiAppContext, tableMap, queryName, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors); } catch (QueryableRecordTableException e) { log.warn("Failed to create optimized Store Query Runtime as no query configuration was found " + <START> "for Store Query: " + storeQuery.toString()); <END> return constructRegularStoreQueryRuntime(table, storeQuery, siddhiAppContext, tableMap, windowMap, queryName, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors, lockWrapper); } } else { return constructRegularStoreQueryRuntime(table, storeQuery, siddhiAppContext, tableMap, windowMap, queryName, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors, lockWrapper); } }</code><technical_language>this print query in proper format</technical_language>

Target:
private static StoreQueryRuntime constructStoreQueryRuntime(Table table, StoreQuery storeQuery, SiddhiAppContext siddhiAppContext, Map<String, Table> tableMap, Map<String, Window> windowMap, String queryName, int metaPosition, Expression onCondition, MetaStreamEvent metaStreamEvent, List<VariableExpressionExecutor> variableExpressionExecutors, LockWrapper lockWrapper) { if (table instanceof QueryableProcessor && storeQuery.getType() == StoreQuery.StoreQueryType.FIND) { try { return constructOptimizedStoreQueryRuntime(table, storeQuery, siddhiAppContext, tableMap, queryName, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors); } catch (QueryableRecordTableException e) { if (log.isDebugEnabled()) { log.debug("Store Query optimization failed for table: " + table.getTableDefinition().getId() + ". Creating Store Query runtime in normal mode. " + "Reason for failure: " + e.getMessage()); } else { log.info("Creating Store Query Runtime in the normal mode, for table: " + table.getTableDefinition().getId()); } return constructRegularStoreQueryRuntime(table, storeQuery, siddhiAppContext, tableMap, windowMap, queryName, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors, lockWrapper); } } else { return constructRegularStoreQueryRuntime(table, storeQuery, siddhiAppContext, tableMap, windowMap, queryName, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors, lockWrapper); } }
Source:
<code><START> public void refreshMapInfoWindow() { <END> mitMapView.getMap().setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() { @Override public View getInfoWindow(Marker marker) { return null; } @Override public View getInfoContents(Marker marker) { if (marker.getTitle() != null) { View view = getActivity().getLayoutInflater().inflate(R.layout.mit_map_info_window, null); TextView stopNameTextView = (TextView) view.findViewById(R.id.stop_name_textview); TextView stopPredictionView = (TextView) view.findViewById(R.id.stop_prediction_textview); stopNameTextView.setText(marker.getTitle()); for (MITShuttleStopWrapper stop : route.getStops()) { if (marker.getSnippet().equals(stop.getId())) { stopNameTextView.setText(stop.getTitle()); if (route.isPredictable()) { if (stop.getPredictions().size() > 0) { if (stop.getPredictions().get(0).getSeconds() / 60 < 1) { stopPredictionView.setText(getString(R.string.arriving_now)); } else { stopPredictionView.setText(getString(R.string.arriving_in) + " " + stop.getPredictions().get(0).getSeconds() / 60 + " " + getString(R.string.minutes)); } } } else if (route.isScheduled()) { stopPredictionView.setText(getString(R.string.route_unknown)); } else { stopPredictionView.setText(getString(R.string.route_not_in_service)); } } } return view; } else { return null; } } }); }</code><technical_language>Instead of creating a new interface time, ShuttleRouteFragment implement InfoWindowAdapter, call setInfoWindowAdapter(this) want refresh</technical_language>

Target:
public void refreshMapInfoWindow() { mitMapView.getMap().setInfoWindowAdapter(this); }
Source:
<code>public InMemoryJarfile deepCopy () { InMemoryJarfile copy = new InMemoryJarfile(); for (Entry<String, byte[]> e: this.entrySet()) { copy.put(e.getKey(), e.getValue()); } copy.m_loader.initFrom(m_loader); <START> return copy; <END> }</code><technical_language>Is this more shallow copy</technical_language>

Target:
public InMemoryJarfile deepCopy () { InMemoryJarfile copy = new InMemoryJarfile(); for (Entry<String, byte[]> e: this.entrySet()) { copy.put(e.getKey(), e.getValue().clone()); } copy.m_loader.initFrom(m_loader); return copy; }
Source:
<code>public void testUnionPointWithEmptyLineString() { <START> assertUnion("POINT (1 2)", "LINESTRING EMPTY", "GEOMETRYCOLLECTION (POINT (1 2))"); <END> }</code><technical_language>expect union of POINT (1, 2) LINESTRING EMPTY POINT (1, 2), this test asserts result GEOMETRYCOLLECTION (POINT (1 2))</technical_language>

Target:
public void testUnionPointWithEmptyLineString() { assertUnion("POINT (1 2)", "LINESTRING EMPTY", "POINT (1 2)"); }
Source:
<code>public void setEnabledAuthProvider(SocialProvider provider) { <START> mDialog.setProviderEnabled(provider); <END> }</code><technical_language>A method called setProviderEnabled() feeling (also) a boolean isEnabled parameter. stick setEnabledProvider() too</technical_language>

Target:
public void setEnabledAuthProvider(SocialProvider provider) { mDialog.setEnabledProvider(provider); }
Source:
<code>private R buildRecord(int offset, int length) { ByteBuffer data = ByteBuffers.getPartialView(currentBuffer, offset, length); <START> final Matcher fileFooterMatcher = fileFooterPattern.matcher(data.asCharBuffer()); <END> if(fileFooterMatcher.matches()){ stopParsing("End of file reached, file footer pattern matched"); return null; } ++recordsFromCurrentBuffer; Preconditions.checkNotNull(currentBufferFile); R record = null; try { record = buildRecord(currentBufferFile, convertData(data), toChannelOffset(offset)); } catch (DataConversionException e) { totalDataProcessingErrors.incrementAndGet(); logger.warn("Cannot process input data: " + e.getMessage() + ", falling back to raw data."); record = buildRecord(currentBufferFile, data, toChannelOffset(offset)); } finally { totalRecordsParsed.incrementAndGet(); } return record; }</code><technical_language>this a performance issue if want do this regex match for record</technical_language>

Target:
private R buildRecord(int offset, int length) { ByteBuffer data = ByteBuffers.getPartialView(currentBuffer, offset, length); if(fileFooterPattern != null){ final Matcher fileFooterMatcher = fileFooterPattern.matcher(data.asCharBuffer()); if(fileFooterMatcher.matches()){ stopParsing("End of file reached, file footer pattern matched"); return null; } } ++recordsFromCurrentBuffer; Preconditions.checkNotNull(currentBufferFile); R record = null; try { record = buildRecord(currentBufferFile, convertData(data), toChannelOffset(offset)); } catch (DataConversionException e) { totalDataProcessingErrors.incrementAndGet(); logger.warn("Cannot process input data: " + e.getMessage() + ", falling back to raw data."); record = buildRecord(currentBufferFile, data, toChannelOffset(offset)); } finally { totalRecordsParsed.incrementAndGet(); } return record; }
Source:
<code>public void excludeAll() { initializeExcludesIfNull(); for(Field field : new Mirror().on(getRootClass()).reflectAll().fields()) { <START> excludes.putAll(field.getName(), getParentTypes(field.getName(), getRootClass())); <END> } }</code><technical_language>remove this initializeExcludesIfNull if getExcludes()</technical_language>

Target:
public void excludeAll() { for(Field field : new Mirror().on(getRootClass()).reflectAll().fields()) { getExcludes().putAll(field.getName(), getParentTypes(field.getName(), getRootClass())); } }
Source:
<code>protected Column(Class<?> tableClass, String fieldName, AggregationDictionary dictionary) { this.id = dictionary.getJsonAliasFor(tableClass) + "." + fieldName; this.name = fieldName; this.columnTags = new HashSet<>(); if (dictionary.isRelation(tableClass, fieldName)) { Class<?> relationshipClass = dictionary.getParameterizedType(tableClass, fieldName); String relationshipName = dictionary.getJsonAliasFor(relationshipClass); this.dataType = new RelationshipType( this.id + "." + relationshipClass.getSimpleName().toLowerCase(Locale.ENGLISH), relationshipName); } else { Class<?> fieldClass = dictionary.getType(tableClass, fieldName); if (dictionary.getIdFieldName(tableClass).equals(fieldName)) { <START> this.dataType = new DataType(dictionary.getJsonAliasFor(tableClass) + "." + fieldName, ValueType.ID); <END> } else if (Date.class.isAssignableFrom(fieldClass)) { this.dataType = new DataType(fieldClass.getSimpleName().toLowerCase(Locale.ENGLISH), ValueType.DATE); } else { DataType dataType = DataType.getScalarType(fieldClass); if (dataType == null) { throw new IllegalArgumentException("Unknown data type for " + this.id); } this.dataType = dataType; } } }</code><technical_language>Do data types need a name</technical_language>

Target:
protected Column(Class<?> tableClass, String fieldName, AggregationDictionary dictionary) { this.tableName = dictionary.getJsonAliasFor(tableClass); this.id = tableName + "." + fieldName; this.name = fieldName; this.columnTags = new HashSet<>(); if (dictionary.isRelation(tableClass, fieldName)) { Class<?> relationshipClass = dictionary.getParameterizedType(tableClass, fieldName); String relationshipName = dictionary.getJsonAliasFor(relationshipClass); this.dataType = new RelationshipType( this.id + "." + relationshipClass.getSimpleName().toLowerCase(Locale.ENGLISH), relationshipName); } else { Class<?> fieldClass = dictionary.getType(tableClass, fieldName); if (dictionary.getIdFieldName(tableClass).equals(fieldName)) { this.dataType = new DataType(tableName + "." + fieldName, ValueType.ID); } else if (Date.class.isAssignableFrom(fieldClass)) { this.dataType = new DataType(fieldClass.getSimpleName().toLowerCase(Locale.ENGLISH), ValueType.DATE); } else { DataType dataType = DataType.getScalarType(fieldClass); if (dataType == null) { throw new IllegalArgumentException("Unknown data type for " + this.id); } this.dataType = dataType; } } }
Source:
<code>public List<QueryResult<StudyAclEntry>> getAcls(List<String> studyList, boolean silent, String sessionId) throws CatalogException { String userId = catalogManager.getUserManager().getUserId(sessionId); List<Long> studyIds = getIds(userId, studyList.get(0)); List<QueryResult<StudyAclEntry>> studyAclList = new ArrayList<>(studyIds.size()); for (Long studyId : studyIds) { try { <START> QueryResult<StudyAclEntry> allStudyAcls = authorizationManager.getAllStudyAcls(userId, studyId); <END> allStudyAcls.setId(String.valueOf(studyId)); studyAclList.add(allStudyAcls); } catch (CatalogException e) { if (silent) { studyAclList.add(new QueryResult<>(String.valueOf(studyId), 0, 0, 0, "", e.toString(), new ArrayList<>(0))); } else { throw e; } } } return studyAclList; }</code><technical_language>Again, ids studyList</technical_language>

Target:
public List<QueryResult<StudyAclEntry>> getAcls(List<String> studyList, boolean silent, String sessionId) throws CatalogException { String userId = catalogManager.getUserManager().getUserId(sessionId); List<Long> studyIds = getIds(userId, studyList.get(0)); List<QueryResult<StudyAclEntry>> studyAclList = new ArrayList<>(studyIds.size()); for (int i = 0; i < studyIds.size(); i++) { Long studyId = studyIds.get(i); try { QueryResult<StudyAclEntry> allStudyAcls = authorizationManager.getAllStudyAcls(userId, studyId); allStudyAcls.setId(String.valueOf(studyId)); studyAclList.add(allStudyAcls); } catch (CatalogException e) { if (silent) { studyAclList.add(new QueryResult<>(studyList.get(i), 0, 0, 0, "", e.toString(), new ArrayList<>(0))); } else { throw e; } } } return studyAclList; }
Source:
<code>public String getTimeAgo(Date date) { if (date == null) { return "N/A"; } long time_ago = date.getTime() / 1000l; long cur_time = new Date().getTime() / 1000l; long time_elapsed = cur_time - time_ago; long seconds = time_elapsed; if (seconds <= 60) { return "Just now"; } else { int minutes = Math.round(time_elapsed / 60); if (minutes <= 60) { if (minutes == 1) { return "A minute ago"; } else { return minutes + " minutes ago"; } } else { int hours = Math.round(time_elapsed / 3600); if (hours <= 24) { if (hours == 1) { return "An hour ago"; } else { return hours + " hours ago"; } } else { int days = Math.round(time_elapsed / 86400); if (days <= 7) { if (days == 1) { return "Yesterday"; } else { return days + " days ago"; } } else { int weeks = Math.round(time_elapsed / 604800); if (weeks <= 4.3) { if (weeks == 1) { return "A week ago"; } else { return weeks + " weeks ago"; } } else { int months = Math.round(time_elapsed / 2600640); if (months <= 12) { if (months == 1) { return "A month ago"; } else { return months + " months ago"; } } else { int years = Math.round(time_elapsed / 31207680); if (years == 1) { <START> return "A year ago"; <END> } else { return years + " years ago"; } } } } } } } }</code><technical_language>year is more deterministic. leave 1 year ago</technical_language>

Target:
public String getTimeAgo(Date date) { if (date == null) { return "N/A"; } long time_ago = date.getTime() / 1000l; long cur_time = new Date().getTime() / 1000l; long time_elapsed = cur_time - time_ago; long seconds = time_elapsed; if (seconds <= 60) { return "Just now"; } else { int minutes = Math.round(time_elapsed / 60); if (minutes <= 60) { if (minutes == 1) { return "A minute ago"; } else { return minutes + " minutes ago"; } } else { int hours = Math.round(time_elapsed / 3600); if (hours <= 24) { if (hours == 1) { return "An hour ago"; } else { return hours + " hours ago"; } } else { int days = Math.round(time_elapsed / 86400); if (days <= 7) { if (days == 1) { return "Yesterday"; } else { return days + " days ago"; } } else { int weeks = Math.round(time_elapsed / 604800); if (weeks <= 4.3) { if (weeks == 1) { return "A week ago"; } else { return weeks + " weeks ago"; } } else { int months = Math.round(time_elapsed / 2600640); if (months <= 12) { if (months == 1) { return "A month ago"; } else { return months + " months ago"; } } else { int years = Math.round(time_elapsed / 31207680); if (years == 1) { return "1 year ago"; } else { return years + " years ago"; } } } } } } } }