auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean canPlaceAt(GlowBlock block, BlockFace against) { <START> return !block.getRelative(BlockFace.DOWN).isEmpty(); <END> }</code><technical_language>world.getTypeId(x, y, z) != 0 I is annoying creating new objects is unnecessary</technical_language>

Target:
public boolean canPlaceAt(GlowBlock block, BlockFace against) { return block.getWorld().getBlockTypeIdAt(block.getX(), block.getY() - 1, block.getZ()) != Material.AIR.getId(); }
Source:
<code>public void expectRedWhenReadingValueIs210WithNoPreferredRange() { <START> reading = 410; <END> assertEquals(glucoseRanges.colorFromReading(reading), "red"); }</code><technical_language>this is strange field default is changed in test method. I a local variable in test</technical_language>

Target:
public void expectRedWhenReadingValueIs210WithNoPreferredRange() { assertEquals(glucoseRanges.colorFromReading(410), "red"); }
Source:
<code>@Override public void run() { try { Thread.currentThread().setName(Utils.THREAD_PREFIX + data.getName()); result = hunt(); if (result == null) { dispatcher.dispatchFailed(this); } else { dispatcher.dispatchComplete(this); } } catch (OutOfMemoryError e) { <START> result = null; <END> dispatcher.dispatchFailed(this); throw(e); } catch (IOException e) { exception = e; dispatcher.dispatchRetry(this); } finally { Thread.currentThread().setName(Utils.THREAD_IDLE_NAME); } }</code><technical_language>This block is indented improperly. spaces (like catch block)</technical_language>

Target:
@Override public void run() { try { Thread.currentThread().setName(Utils.THREAD_PREFIX + data.getName()); result = hunt(); if (result == null) { dispatcher.dispatchFailed(this); } else { dispatcher.dispatchComplete(this); } } catch (OutOfMemoryError e) { result = null; dispatcher.dispatchFailed(this); throw e; } catch (IOException e) { exception = e; dispatcher.dispatchRetry(this); } finally { Thread.currentThread().setName(Utils.THREAD_IDLE_NAME); } }
Source:
<code>private VmPropertiesUtils mockVmPropertiesUtils() throws InitializationException { VmPropertiesUtils utils = spy(new VmPropertiesUtils()); doReturn("sap_agent=^(true|false)$;sndbuf=^[0-9]+$;" + "vhost=^(([a-zA-Z0-9_]*):(true|false))(,(([a-zA-Z0-9_]*):(true|false)))*$;" + "viodiskcache=^(none|writeback|writethrough)$;" + <START> "mdev_type=^.*$;hugepages=^(true|false)|([0-9]+)$;hugepagesz=^[0-9]+$"). <END> when(utils) .getPredefinedVMProperties(any(Version.class)); doReturn(""). when(utils) .getUserdefinedVMProperties(any(Version.class)); doReturn(new HashSet<>(Arrays.asList(Version.v3_6, Version.v4_0))). when(utils) .getSupportedClusterLevels(); doReturn(utils).when(runVmValidator).getVmPropertiesUtils(); utils.init(); return utils; }</code><technical_language>hugepagesz in properties, define this property in ConfigValues, why</technical_language>

Target:
private VmPropertiesUtils mockVmPropertiesUtils() throws InitializationException { VmPropertiesUtils utils = spy(new VmPropertiesUtils()); doReturn("sap_agent=^(true|false)$;sndbuf=^[0-9]+$;" + "vhost=^(([a-zA-Z0-9_]*):(true|false))(,(([a-zA-Z0-9_]*):(true|false)))*$;" + "viodiskcache=^(none|writeback|writethrough)$;" + "mdev_type=^.*$;hugepages=^[0-9]+$"). when(utils) .getPredefinedVMProperties(any(Version.class)); doReturn(""). when(utils) .getUserdefinedVMProperties(any(Version.class)); doReturn(new HashSet<>(Arrays.asList(Version.v3_6, Version.v4_0))). when(utils) .getSupportedClusterLevels(); doReturn(utils).when(runVmValidator).getVmPropertiesUtils(); utils.init(); return utils; }
Source:
<code><START> public int run(String[] args) { <END> initJCommander(); try { parseParams(jc, args); if (help) { printUsage(null); return EXIT_CODE_OK; } if (debug) { initializeDebugLogging(); } if (jc.getParsedCommand() == null) { return handleNoCommand(); } if (!commands.containsKey(jc.getParsedCommand())) { LOGGER.error("Unknown command: " + jc.getParsedCommand()); return EXIT_CODE_ERR; } Command parsedCommand = commands.get(jc.getParsedCommand()); if (CommandHelp.CLINAME.equals(parsedCommand.getName())) { printUsage(null); } else { if (parsedCommand.validateParameters()) { parsedCommand.execute(); } else { printUsage(jc.getParsedCommand()); return EXIT_CODE_ERR; } } return EXIT_CODE_OK; } catch (Exception ex) { return EXIT_CODE_ERR; } }</code><technical_language>![MAJOR](<LINK_0> Cyclomatic Complexity of this method "run" is 14 is greater 10 authorized. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public int run(String[] args) { initJCommander(); try { parseParams(jc, args); if (help) { printUsage(null); return EXIT_CODE_OK; } if (debug) { initializeDebugLogging(); } if (jc.getParsedCommand() == null) { return handleNoCommand(); } if (!commands.containsKey(jc.getParsedCommand())) { LOGGER.error("Unknown command: " + jc.getParsedCommand()); return EXIT_CODE_ERR; } Command parsedCommand = commands.get(jc.getParsedCommand()); if (CommandHelp.CLINAME.equals(parsedCommand.getName())) { printUsage(null); } else { if (parsedCommand.validateParameters()) { parsedCommand.execute(); } else { printUsage(jc.getParsedCommand()); return EXIT_CODE_ERR; } } return EXIT_CODE_OK; } catch (Exception ex) { LOGGER.debug("Exception while processing", ex); return EXIT_CODE_ERR; } }
Source:
<code>private Intent getSortType() { <START> Spinner sort_type_spinner = (Spinner) findViewById(R.id.sort_type_spinner); <END> String sort_type = sort_type_spinner.getSelectedItem().toString(); Spinner sort_time_spinner = (Spinner) findViewById(R.id.sort_time_spinner); String sort_time = sort_time_spinner.getSelectedItem().toString(); adapter = ExpenseClaimListActivity.getAdapter(); claims = ExpenseClaimListActivity.getClaims(); String type1 = "Date of Travel"; String type2 = "Order of Entry"; String time1 = "Ascending"; if (type1.equals(sort_type)) { if (time1.equals(sort_time)) { Collections.sort(claims, new StartDateAscendingComparator()); commitClaimsMutation(); } else { Collections.sort(claims, new StartDateDescendingComparator()); commitClaimsMutation(); } } else if (type2.equals(sort_type)) { if (time1.equals(sort_time)) { Collections.sort(claims, new CreationDateAscendingComparator()); commitClaimsMutation(); } else { Collections.sort(claims, new CreationDateDescendingComparator()); commitClaimsMutation(); } } Intent intent = new Intent(); return intent; }</code><technical_language>camelCase for variable names underscores</technical_language>

Target:
private Intent getSortType() { Spinner sortTypeSpinner = (Spinner)findViewById(R.id.sort_type_spinner); String sortType = sortTypeSpinner.getSelectedItem().toString(); Spinner sortOrderSpinner = (Spinner) findViewById(R.id.sort_order_spinner); String sortOrder = sortOrderSpinner.getSelectedItem().toString(); String type1 = "Date of Travel"; String type2 = "Order of Entry"; String time1 = "Ascending"; Intent intent = new Intent(); if (type1.equals(sortType)) { if (time1.equals(sortOrder)) { intent.putExtra(EXPENSE_CLAIM_SORT, new StartDateAscendingComparator()); } else { intent.putExtra(EXPENSE_CLAIM_SORT, new StartDateDescendingComparator()); } } else if (type2.equals(sortType)) { if (time1.equals(sortOrder)) { intent.putExtra(EXPENSE_CLAIM_SORT, new CreationDateAscendingComparator()); } else { intent.putExtra(EXPENSE_CLAIM_SORT, new CreationDateDescendingComparator()); } } return intent; }
Source:
<code>public String getPrintString(IAdaptable element, int flags) { StereotypeDisplayHelper helper = StereotypeDisplayHelper.getInstance(); if (element instanceof IAdaptable) { final Property property = ((Property) (EMFHelper.getEObject(element))); final View view = ((View) element.getAdapter(View.class)); StereotypeLocationEnum location; if (helper.isInStereotypeComment((Node) view)) { location = StereotypeLocationEnum.IN_COMMENT_COMPARTMENT; } else { location = StereotypeLocationEnum.IN_COMPARTMENT; } if (view != null && property != null) { return helper.getStereotypePropertyToDisplay(view, property, location); } } return <START> "<UNDEFINED>"; <END> }</code><technical_language>a constant</technical_language>

Target:
public String getPrintString(IAdaptable element, int flags) { StereotypeDisplayHelper helper = StereotypeDisplayHelper.getInstance(); if (element instanceof IAdaptable) { final Property property = ((Property) (EMFHelper.getEObject(element))); final View view = ((View) element.getAdapter(View.class)); StereotypeLocationEnum location; if (helper.isInStereotypeComment((Node) view)) { location = StereotypeLocationEnum.IN_COMMENT_COMPARTMENT; } else { location = StereotypeLocationEnum.IN_COMPARTMENT; } if (view != null && property != null) { return helper.getStereotypePropertyToDisplay(view, property, location); } } return DEFAULT_VALUE; }
Source:
<code>public Object parse(final StaplerRequest request, final StringBodyParameter a, final Class type, final String parameterName) throws ServletException { final String contentType = request.getContentType(); <START> if ("application/json".equals(contentType)) { <END> try { return IOUtils.toString(request.getInputStream(), Charsets.UTF_8); } catch (final IOException e) { LOGGER.log(Level.SEVERE, "Unable to obtain request body: {}", e.getMessage()); } } else if ("application/x-www-form-urlencoded".equals(contentType)) { return request.getParameter(parameterName); } return null; }</code><technical_language>Is javax.ws.rs.core.MediaType.APPLICATION_JSON here</technical_language>

Target:
public Object parse(final StaplerRequest request, final StringBodyParameter a, final Class type, final String parameterName) throws ServletException { final String rawContentType = request.getContentType(); final String contentType = StringHelper.determineContentTypeWithoutCharset(rawContentType); if (MediaType.APPLICATION_JSON.equals(contentType)) { final String characterEncoding = request.getCharacterEncoding(); try { return IOUtils.toString(request.getInputStream(), characterEncoding); } catch (final IOException e) { LOGGER.log(Level.SEVERE, "Unable to obtain request body: {}", e.getMessage()); } } else if (MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)) { return request.getParameter(parameterName); } return null; }
Source:
<code>public ReplicaSetConfig member(String hostname, Integer port, Integer id) { if (members.size() == MAXIMUM_REPLICA_SET_SIZE) { throw new IllegalStateException(String.format( "Replica set exceeds maximum size of with addition of member at {}:{}", new Object[]{name, MAXIMUM_REPLICA_SET_SIZE, hostname, port})); } BasicBSONObject member = new BasicBSONObject(); member.put("_id", id); member.put("host", String.format("%s:%s", hostname, port)); if (members.contains(member)) { <START> LOG.warn("Ignoring attempt to add entity to a set of which it is already a member"); <END> return this; } members.add(member); return this; }</code><technical_language>this case happen? Suggests calling code needs fixed</technical_language>

Target:
public ReplicaSetConfig member(String hostname, Integer port, Integer id) { if (members.size() == MAXIMUM_REPLICA_SET_SIZE) { throw new IllegalStateException(String.format( "Replica set exceeds maximum size of with addition of member at {}:{}", new Object[]{name, MAXIMUM_REPLICA_SET_SIZE, hostname, port})); } BasicBSONObject member = new BasicBSONObject(); member.put("_id", id); member.put("host", String.format("%s:%s", hostname, port)); members.add(member); return this; }
Source:
<code><START> public ConnectionConfiguration(SSLContextFactory sslContextFactory) { <END> this.sslContextFactory = sslContextFactory; brokerHosts = new ArrayList<>(); username = "guest"; password = "guest"; this.connectTimeout = DEFAULT_CONNECT_TIMEOUT_IN_MS; this.requestedConnectionHeartbeatTimeout = DEFAULT_CONNECTION_HEARTBEAT_TIMEOUT_IN_SEC; this.connectRetryWaitTime = DEFAULT_WAIT_TIME_RETRY_CONNECT_IN_MS; this.failedConsumerActivationRetryTime = DEFAULT_WAIT_TIME_RETRY_ACTIVATE_CONSUMER_IN_MS; }</code><technical_language>Public access relay needed</technical_language>

Target:
ConnectionConfiguration(SSLContextFactory sslContextFactory) { this.sslContextFactory = sslContextFactory; brokerHosts = new ArrayList<>(); username = "guest"; password = "guest"; this.connectTimeout = DEFAULT_CONNECT_TIMEOUT_IN_MS; this.requestedConnectionHeartbeatTimeout = DEFAULT_CONNECTION_HEARTBEAT_TIMEOUT_IN_SEC; this.connectRetryWaitTime = DEFAULT_WAIT_TIME_RETRY_CONNECT_IN_MS; this.failedConsumerActivationRetryTime = DEFAULT_WAIT_TIME_RETRY_ACTIVATE_CONSUMER_IN_MS; }
Source:
<code>public static int execute(List<String> command) throws Exception { logger.info(command.toString()); ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); final Process process = builder.start(); StringBuilder bashLog = new StringBuilder(); try ( InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr) ) { String line; while ((line = br.readLine()) != null) { logger.info(line); bashLog.append(line); } process.waitFor(); <START> if (process.exitValue() != 0) { <END> bashLog.append(command.toString()); throw new NetCdfProcessingException(bashLog.toString()); } return process.exitValue(); } catch (InterruptedException e) { logger.error(String.format("Interrupted: '%s'", e.getMessage())); throw e; } catch (NetCdfProcessingException e) { logger.error(String.format("NetCdf Tool Error: '%s'", e.getMessage())); throw e; } }</code><technical_language>a bit concerned handling of process. In testing, exception is thrown bubbled time exit for process, damage done file created (and returned). get exception in catalina log. So, suggestion consider setting processListener.isCancelled(true) throw a GGD exception. Needs testing validation of course</technical_language>

Target:
public static int execute(List<String> command) throws Exception { logger.info(command.toString()); ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); final Process process = builder.start(); StringBuilder bashLog = new StringBuilder(); try ( InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr) ) { String line; while ((line = br.readLine()) != null) { logger.info(line); bashLog.append(line); } process.waitFor(); if (process.exitValue() != 0) { bashLog.append(command.toString()); throw new NetCdfProcessingException(bashLog.toString()); } return process.exitValue(); } catch (InterruptedException e) { logger.error(String.format("Interrupted: '%s'", e.getMessage()), e); throw e; } catch (NetCdfProcessingException e) { logger.error(String.format("NetCdf Tool Error: '%s'", e.getMessage()), e); throw e; } }
Source:
<code>public void uploadFile(AbstractBackupPath path, InputStream in, long chunkSize) throws BackupRestoreException { if (path.getSize() < chunkSize) { if (logger.isDebugEnabled()) logger.debug("Uploading file using put: {}", path.getRemotePath()); try { byte[] chunk = compress.compress(in); rateLimiter.acquire(chunk.length); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(chunk.length); PutObjectRequest putObjectRequest = new PutObjectRequest(config.getBackupPrefix(), path.getRemotePath(), new ByteArrayInputStream(chunk), objectMetadata); PutObjectResult upload = new BoundedExponentialRetryCallable<PutObjectResult>() { @Override public PutObjectResult retriableCall() throws Exception { return s3Client.putObject(putObjectRequest); } }.retriableCall(); bytesUploaded.addAndGet(chunk.length); if (logger.isDebugEnabled()) logger.debug("Successfully uploaded file with putObject: and etag: {}", path.getRemotePath(), upload.getETag()); <START> }catch (Exception e) { <END> throw encounterError(path, e); } finally { IOUtils.closeQuietly(in); } }else uploadMultipart(path, in, chunkSize); }</code><technical_language>nit: space</technical_language>

Target:
public void uploadFile(AbstractBackupPath path, InputStream in, long chunkSize) throws BackupRestoreException { if (path.getSize() < chunkSize) { if (logger.isDebugEnabled()) logger.debug("Uploading file using put: {}", path.getRemotePath()); try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { Iterator<byte[]> chunkedStream = compress.compress(in, chunkSize); while (chunkedStream.hasNext()) { byteArrayOutputStream.write(chunkedStream.next()); } byte[] chunk = byteArrayOutputStream.toByteArray(); rateLimiter.acquire(chunk.length); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(chunk.length); PutObjectRequest putObjectRequest = new PutObjectRequest(config.getBackupPrefix(), path.getRemotePath(), new ByteArrayInputStream(chunk), objectMetadata); PutObjectResult upload = new BoundedExponentialRetryCallable<PutObjectResult>() { @Override public PutObjectResult retriableCall() throws Exception { return s3Client.putObject(putObjectRequest); } }.retriableCall(); bytesUploaded.addAndGet(chunk.length); if (logger.isDebugEnabled()) logger.debug("Successfully uploaded file with putObject: and etag: {}", path.getRemotePath(), upload.getETag()); } catch (Exception e) { throw encounterError(path, e); } finally { IOUtils.closeQuietly(in); } } else uploadMultipart(path, in, chunkSize); }
Source:
<code>public void addOrder(Order order, Integer position) { if (order == null || getOrders().contains(order)) return; position = position == null ? getOrders().size() : position - 1; getOrders().add(position, order); <START> if (order.getSortWeight() == null) <END> order.setSortWeight(findSortWeight(position)); }</code><technical_language>convention is include curly braces if clauses</technical_language>

Target:
public void addOrder(Order order, Integer position) { if (order == null || getOrders().contains(order)) { return; } Integer listIndex = findListIndexForGivenPosition(position); getOrders().add(listIndex, order); if (order.getSortWeight() == null) { order.setSortWeight(findSortWeight(listIndex)); } }
Source:
<code>protected void setClampHeight(float value) throws AutonomousModeOverException, InterruptedException { <START> Clamp.heightOrSpeed.set(value); <END> waitUntil(FloatMixing.floatIsInRange(Clamp.heightReadout, value - clampHeightPadding.get(), value + clampHeightPadding.get())); }</code><technical_language>set mode setClampHeight set height</technical_language>

Target:
protected void setClampHeight(float value) throws AutonomousModeOverException, InterruptedException { Clamp.mode.set(false); Clamp.heightOrSpeed.set(value); waitUntil(FloatMixing.floatIsInRange(Clamp.heightReadout, value - clampHeightPadding.get(), value + clampHeightPadding.get())); }
Source:
<code>protected @NonNull List<@NonNull TmfTreeDataModel> getTree(@NonNull ITmfStateSystem ss, @NonNull TimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { List<@NonNull Integer> attribs = ss.getSubAttributes(ITmfStateSystem.ROOT_ATTRIBUTE, false); List<@NonNull TmfTreeDataModel> retVal = new ArrayList<>(); for (Integer attrib : attribs) { String[] <START> strings = <END> fCache.computeIfAbsent(attrib, t -> ss.getFullAttributePathArray(t)); retVal.add(new TmfTreeDataModel(getId(attrib), getId(ITmfStateSystem.ROOT_ATTRIBUTE), strings[0])); } return retVal; }</code><technical_language>need this, ss.getAttributeName</technical_language>

Target:
protected @NonNull List<@NonNull TimeGraphEntryModel> getTree(@NonNull ITmfStateSystem ss, @NonNull TimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { long rootId = getId(ITmfStateSystem.ROOT_ATTRIBUTE); List<@NonNull Integer> attribs = ss.getSubAttributes(ITmfStateSystem.ROOT_ATTRIBUTE, false); List<@NonNull TimeGraphEntryModel> retVal = new ArrayList<>(); for (Integer attrib : attribs) { String[] strings = ss.getFullAttributePathArray(attrib); retVal.add(new TimeGraphEntryModel(getId(attrib), rootId, strings[0], ss.getStartTime(), ss.getCurrentEndTime())); } return retVal; }
Source:
<code>public List<VDS> filter(List<VDS> hosts, VM vm, Map<String, String> parameters, List<String> messages) { if (vm.isHostedEngine()) { List<VDS> hostsToRunOn = new ArrayList<VDS>(); for (VDS host : hosts) { if (host.getDynamicData().getHighlyAvailableScore() != 0 ) { hostsToRunOn.add(host); log.debugFormat("Host {0} wasn't filtered out as it has a score of {1}", host.getName(), host.getDynamicData().getHighlyAvailableScore()); <START> } else { <END> log.debugFormat("Host {0} was filtered out as it doesn't have a positive score", host.getName()); } } if (hostsToRunOn.isEmpty()) { messages.add(VdcBllMessages.ACTION_TYPE_FAILED_NO_HA_VDS.toString()); } return hostsToRunOn; } else { return hosts; } }</code><technical_language>check if is score != 0 > 0 log positive. if score contract (VDSM API) is negative this check check >0 if negative score a meaning reflected here</technical_language>

Target:
public List<VDS> filter(List<VDS> hosts, VM vm, Map<String, String> parameters, List<String> messages) { if (vm.isHostedEngine()) { List<VDS> hostsToRunOn = new ArrayList<VDS>(); for (VDS host : hosts) { int haScore = host.getDynamicData().getHighlyAvailableScore(); if (haScore > 0) { hostsToRunOn.add(host); log.debugFormat("Host {0} wasn't filtered out as it has a score of {1}", host.getName(), haScore); } else { log.debugFormat("Host {0} was filtered out as it doesn't have a positive score (the score is {1})", host.getName(), haScore); } } if (hostsToRunOn.isEmpty()) { messages.add(VdcBllMessages.ACTION_TYPE_FAILED_NO_HA_VDS.name()); } return hostsToRunOn; } else { return hosts; } }
Source:
<code>private ElementTag createCancelAddInstructorButton() { String buttonContent = "<span class=\"glyphicon glyphicon-remove\"></span> Cancel"; <START> String buttonId = "newInstrCancelLink"; <END> return createBasicButton(buttonContent, buttonId, "javascript:;", Const.Tooltips.COURSE_INSTRUCTOR_CANCEL_ADD, false); }</code><technical_language>umm want change id? this sounds if is a link this button gonna direct another page..</technical_language>

Target:
private ElementTag createCancelAddInstructorButton() { String buttonContent = "<span class=\"glyphicon glyphicon-remove\"></span> Cancel"; String buttonId = "cancelAddInstructorLink"; return createBasicButton(buttonContent, buttonId, "javascript:;", Const.Tooltips.COURSE_INSTRUCTOR_CANCEL_ADD, false); }
Source:
<code>private void fetchUsersList(String dotComBlogId, final int localTableBlogId, final int offset) { if (mPeopleEndOfListReached) { return; } FragmentManager fragmentManager = getFragmentManager(); final PeopleListFragment peopleListFragment = (PeopleListFragment) fragmentManager .findFragmentByTag(KEY_PEOPLE_LIST_FRAGMENT); <START> if (peopleListFragment != null && offset > 0) { <END> peopleListFragment.showLoadingProgress(true); } PeopleUtils.fetchUsers(dotComBlogId, localTableBlogId, offset, new PeopleUtils.FetchUsersCallback() { @Override public void onSuccess(List<Person> peopleList, boolean isEndOfList) { boolean isFreshList = (offset == 0); mPeopleEndOfListReached = isEndOfList; PeopleTable.savePeople(peopleList, localTableBlogId, isFreshList); refreshOnScreenFragmentDetails(); if (peopleListFragment != null) { peopleListFragment.showLoadingProgress(false); } } @Override public void onError() { if (peopleListFragment != null) { peopleListFragment.showLoadingProgress(false); } ToastUtils.showToast(PeopleManagementActivity.this, R.string.error_fetch_people_list, ToastUtils.Duration.LONG); } }); }</code><technical_language>loading indicator time people list is shown, user is left empty screen request completes. a progress bar list is empty</technical_language>

Target:
private void fetchUsersList(String dotComBlogId, final int localTableBlogId, final int offset) { if (mPeopleEndOfListReached || mFetchRequestInProgress || !NetworkUtils.checkConnection(this)) { return; } FragmentManager fragmentManager = getFragmentManager(); final PeopleListFragment peopleListFragment = (PeopleListFragment) fragmentManager .findFragmentByTag(KEY_PEOPLE_LIST_FRAGMENT); if (peopleListFragment != null) { peopleListFragment.showLoadingProgress(true); } mFetchRequestInProgress = true; PeopleUtils.fetchUsers(dotComBlogId, localTableBlogId, offset, new PeopleUtils.FetchUsersCallback() { @Override public void onSuccess(List<Person> peopleList, boolean isEndOfList) { boolean isFreshList = (offset == 0); mPeopleEndOfListReached = isEndOfList; PeopleTable.savePeople(peopleList, localTableBlogId, isFreshList); refreshOnScreenFragmentDetails(); mFetchRequestInProgress = false; if (peopleListFragment != null) { peopleListFragment.showLoadingProgress(false); } } @Override public void onError() { mFetchRequestInProgress = false; if (peopleListFragment != null) { peopleListFragment.showLoadingProgress(false); } ToastUtils.showToast(PeopleManagementActivity.this, R.string.error_fetch_people_list, ToastUtils.Duration.LONG); } }); }
Source:
<code>public void sawClient(Client client, @Nullable Principal principal) { Instant now = Instant.now(); Instant lastSeen = Optional.ofNullable(client.getLastSeen()) .map(ls -> Instant.ofEpochSecond(ls.toEpochSecond())) .orElse(EPOCH); final Instant expiration; if (principal instanceof CertificatePrincipal) { expiration = Optional.ofNullable((CertificatePrincipal) principal) .map(p -> p.getCertificateExpiration()) .orElse(EPOCH); } else { expiration = EPOCH; } if (now.isAfter(lastSeen.plus(LAST_SEEN_THRESHOLD))) { dslContext.transaction(configuration -> { Param<Long> lastSeenValue = DSL.val(now.getEpochSecond(), CLIENTS.LASTSEEN); Param<Long> expirationValue = DSL.val(expiration.getEpochSecond(), CLIENTS.EXPIRATION); DSL.using(configuration) .update(CLIENTS) .set(CLIENTS.LASTSEEN, when(CLIENTS.LASTSEEN.isNull(), lastSeenValue) .otherwise(greatest(CLIENTS.LASTSEEN, lastSeenValue))) .set(CLIENTS.EXPIRATION, when(CLIENTS.EXPIRATION.isNull(), expirationValue) <START> .otherwise(greatest(CLIENTS.EXPIRATION, expirationValue))) <END> .where(CLIENTS.ID.eq(client.getId())) .execute(); }); } }</code><technical_language>This assumes client present a certificate expires a certificate previously. safer overwrite recorded expiration just-seen expiration</technical_language>

Target:
public void sawClient(Client client, @Nullable Principal principal) { Instant now = Instant.now(); Instant lastSeen = Optional.ofNullable(client.getLastSeen()) .map(ls -> Instant.ofEpochSecond(ls.toEpochSecond())) .orElse(EPOCH); final Instant expiration; if (principal instanceof CertificatePrincipal) { expiration = Optional.ofNullable((CertificatePrincipal) principal) .map(p -> p.getCertificateExpiration()) .orElse(EPOCH); } else { expiration = EPOCH; } if (now.isAfter(lastSeen.plus(LAST_SEEN_THRESHOLD))) { dslContext.transaction(configuration -> { Param<Long> lastSeenValue = DSL.val(now.getEpochSecond(), CLIENTS.LASTSEEN); Param<Long> expirationValue = DSL.val(expiration.getEpochSecond(), CLIENTS.EXPIRATION); DSL.using(configuration) .update(CLIENTS) .set(CLIENTS.LASTSEEN, when(CLIENTS.LASTSEEN.isNull(), lastSeenValue) .otherwise(greatest(CLIENTS.LASTSEEN, lastSeenValue))) .set(CLIENTS.EXPIRATION, expirationValue) .where(CLIENTS.ID.eq(client.getId())) .execute(); }); } }
Source:
<code>public boolean acquire(K key, final Runnable cacheHit) { try (Scope ss = tracer.spanBuilder("DistributedRateLimitedCache").startScopedSpan()) { Span span = tracer.getCurrentSpan(); if (cache.get(key) != null) { span.addAnnotation("Found key in cache"); cacheHit.run(); return false; } final String cacheKey = buildKey(key); try { if (memcachedClient.get( cacheKey).toCompletableFuture().get(100, TimeUnit.MILLISECONDS) != null) { span.addAnnotation("Found key in memcached"); cache.putIfAbsent(key, true); cacheHit.run(); return false; } } catch (TimeoutException | InterruptedException | ExecutionException e) { <START> span.addAnnotation("Failed to get key from memcached"); <END> log.error("Failed to get key from memecached", e); } span.addAnnotation("Acquiring rate limiter"); rateLimiter.acquire(); span.addAnnotation("Acquired rate limiter"); if (cache.putIfAbsent(key, true) != null) { cacheHit.run(); return false; } else { span.addAnnotation("Add key in memcached " + cacheKey); memcachedClient.set(cacheKey, "true", memcachedTtlSeconds); } return true; } }</code><technical_language>nice set span status more visible failed</technical_language>

Target:
public boolean acquire(K key, final Runnable cacheHit) { try (Scope ss = tracer.spanBuilder("DistributedRateLimitedCache").startScopedSpan()) { Span span = tracer.getCurrentSpan(); if (cache.get(key) != null) { span.addAnnotation("Found key in cache"); cacheHit.run(); return false; } final String cacheKey = buildKey(key); try { if (memcachedClient.get( cacheKey).toCompletableFuture().get(100, TimeUnit.MILLISECONDS) != null) { span.addAnnotation("Found key in memcached"); cache.putIfAbsent(key, true); cacheHit.run(); return false; } } catch (TimeoutException | InterruptedException | ExecutionException e) { span.setStatus(Status.INTERNAL.withDescription(e.getMessage())); log.error("Failed to get key from memecached", e); } span.addAnnotation("Acquiring rate limiter"); rateLimiter.acquire(); span.addAnnotation("Acquired rate limiter"); if (cache.putIfAbsent(key, true) != null) { cacheHit.run(); return false; } else { span.addAnnotation("Add key in memcached " + cacheKey); memcachedClient.set(cacheKey, "true", memcachedTtlSeconds); } return true; } }
Source:
<code>public void onInit( String clientName, Map<String,Object> credentials ) throws IOException { <START> packer.packStructHeader( 1, INIT.signature() ); <END> packer.pack( clientName ); packer.pack( ValueUtils.asMapValue( credentials ) ); onMessageComplete.onMessageComplete(); }</code><technical_language>This is wrong is error propagated drivers. init struct size 2 size 1. saved ignoring struct size read init message</technical_language>

Target:
public void onInit( String clientName, Map<String,Object> credentials ) throws IOException { packer.packStructHeader( 2, INIT.signature() ); packer.pack( clientName ); packer.pack( ValueUtils.asMapValue( credentials ) ); onMessageComplete.onMessageComplete(); }
Source:
<code>private void activateViewpoints(List<?> selection) { List<RepresentationItemImpl> representationItemList = getRepresentationItems(selection); Set<Viewpoint> viewpointsToActivate = new HashSet<>(); for (RepresentationItemImpl representationItemImpl : representationItemList) { <START> Object parent = representationItemImpl.getParent(); if (parent instanceof RepresentationDescriptionItemImpl) { <END> RepresentationDescriptionItemImpl representationDescriptionItem = (RepresentationDescriptionItemImpl) parent; boolean activateViewpoint = !ViewpointHelper.isViewpointEnabledInSession(session, representationDescriptionItem.getViewpoint()); if (activateViewpoint) { viewpointsToActivate.add(representationDescriptionItem.getViewpoint()); } } } if (!viewpointsToActivate.isEmpty()) { ViewpointHelper.handleViewpointActivation(session, viewpointsToActivate, true, false); } }</code><technical_language>This assumptions content provider organizes items. break if add diffrent ways organize items, needed. a RepresentationItemImpl corresponds a representation( descriptor), more reliable navigate in actual underlying data model instead of UI elements; like: new RepresentationDescriptionQuery(representationItemImpl.getDRepresentationDescriptor().getDescription()).getParentViewpoint() (with null-checks)</technical_language>

Target:
private void activateViewpoints(List<?> selection) { List<RepresentationItemImpl> representationItemList = getRepresentationItems(selection); Set<Viewpoint> viewpointsToActivate = new HashSet<>(); for (RepresentationItemImpl representationItemImpl : representationItemList) { Viewpoint parentViewpoint = ViewpointHelper.getViewpointInVSM(session, new RepresentationDescriptionQuery(representationItemImpl.getDRepresentationDescriptor().getDescription()).getParentViewpoint()); if (parentViewpoint != null) { boolean activateViewpoint = !ViewpointHelper.isViewpointEnabledInSession(session, parentViewpoint); if (activateViewpoint) { viewpointsToActivate.add(parentViewpoint); } } } if (!viewpointsToActivate.isEmpty()) { ViewpointHelper.handleViewpointActivation(session, viewpointsToActivate, true, false); } }
Source:
<code>public void testNoDataNodesOnFlush() throws Exception { boolean failed = false; cnt = 0; noNodesFilter = true; try { Ignite ignite = startGrid(1); IgniteFuture fut = null; try (IgniteDataStreamer<Integer, String> streamer = ignite.dataStreamer(DEFAULT_CACHE_NAME)) { fut = streamer.addData(1, "1"); streamer.flush(); } <START> catch (CacheException ignored) { <END> try { fut.get(); fail("DataStreamer ignores failed streaming."); } catch (CacheServerNotFoundException ignored2) { } failed = true; } } finally { noNodesFilter = false; assertTrue(failed); } }</code><technical_language>exception type changed</technical_language>

Target:
public void testNoDataNodesOnFlush() throws Exception { boolean failed = false; cnt = 0; noNodesFilter = true; try { Ignite ignite = startGrid(1); IgniteFuture fut = null; try (IgniteDataStreamer<Integer, String> streamer = ignite.dataStreamer(DEFAULT_CACHE_NAME)) { streamer.perThreadBufferSize(1); fut = streamer.addData(1, "1"); streamer.flush(); } catch (IllegalStateException ignored) { try { fut.get(); fail("DataStreamer ignores failed streaming."); } catch (CacheServerNotFoundException ignored2) { } failed = true; } } finally { noNodesFilter = false; assertTrue(failed); } }
Source:
<code>public void testProjectLockableAccount() { AccountVO accountVO = new AccountVO(); accountVO.setId(7L); accountVO.setDomainId(1L); accountVO.setType(Account.ACCOUNT_TYPE_PROJECT); <START> assertFalse(quotaManager.isLockable(accountVO)); <END> }</code><technical_language>@abhinandanprateek remove setId setDomainId in testxxxLockableAccounts; create a single class leve AccountVO in of testxxxLockableAccounts methods simply call setType method call assert them</technical_language>

Target:
public void testProjectLockableAccount() { accountVO.setType(Account.ACCOUNT_TYPE_PROJECT); assertFalse(quotaManager.isLockable(accountVO)); }
Source:
<code>public void useDefaultKeyPair() throws KeyStoreException { String alias = Config.<String>GetValue(ConfigValues.CertAlias); String p12 = Config.<String>GetValue(ConfigValues.keystoreUrl); String password = Config.<String>GetValue(ConfigValues.keystorePass); KeyStore.PrivateKeyEntry entry; InputStream in = null; try { in = new FileInputStream(p12); KeyStore ks = KeyStore.getInstance("PKCS12"); <START> ks.load(in, password.toCharArray()); <END> entry = (KeyStore.PrivateKeyEntry)ks.getEntry( alias, new KeyStore.PasswordProtection( password.toCharArray() ) ); } catch (Exception e) { throw new KeyStoreException( String.format( "Failed to get certificate entry from key store: %1$s/%2$s", p12, alias ), e ); } finally { if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } if (entry == null) { throw new KeyStoreException( String.format( "Bad key store: %1$s/%2$s", p12, alias ) ); } setKeyPair( new KeyPair( entry.getCertificate().getPublicKey(), entry.getPrivateKey() ) ); }</code><technical_language>clear password in memory is bad ..</technical_language>

Target:
public void useDefaultKeyPair() throws KeyStoreException { String alias = Config.<String>GetValue(ConfigValues.CertAlias); String p12 = Config.<String>GetValue(ConfigValues.keystoreUrl); char password[] = Config.<String>GetValue(ConfigValues.keystorePass).toCharArray(); KeyStore.PrivateKeyEntry entry; InputStream in = null; try { in = new FileInputStream(p12); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(in, password); entry = (KeyStore.PrivateKeyEntry)ks.getEntry( alias, new KeyStore.PasswordProtection(password) ); } catch (Exception e) { throw new KeyStoreException( String.format( "Failed to get certificate entry from key store: %1$s/%2$s", p12, alias ), e ); } finally { Arrays.fill(password, '*'); if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } if (entry == null) { throw new KeyStoreException( String.format( "Bad key store: %1$s/%2$s", p12, alias ) ); } setKeyPair( new KeyPair( entry.getCertificate().getPublicKey(), entry.getPrivateKey() ) ); }
Source:
<code>private Map.Entry<String, Object> jsonEntryToMetacardEntry(Map.Entry<String, Object> entry) { try { return transformations .stream() .filter(transformation -> entry.getKey().equals(transformation.getJsonKey())) .findAny() .flatMap( <START> transformation -> { <END> if (transformation.getExpectedJsonType().isInstance(entry.getValue())) { final String newKey = transformation.getMetacardKey(); final Object newValue = transformation.jsonValueToMetacardValue( this, transformation.getExpectedJsonType().cast(entry.getValue())); return Optional.of( (Map.Entry<String, Object>) new AbstractMap.SimpleEntry<>(newKey, newValue)); } else { LOGGER.warn( "A workspace transformation expected a value of type for key \"{}\", but instead found a value of type {}!", transformation.getExpectedJsonType().getName(), entry.getKey(), entry.getValue().getClass().getName()); return Optional.empty(); } }) .orElse(entry); } catch (Throwable exception) { return null; } }</code><technical_language>I this more readable if this extracted a separate method</technical_language>

Target:
private Optional<Map.Entry<String, Object>> jsonEntryToMetacardEntry( Map.Entry<String, Object> entry) { return transformations .stream() .filter(transformation -> entry.getKey().equals(transformation.getJsonKey())) .findAny() .map(transformation -> jsonEntryToMetacardEntry(entry, transformation)) .orElse(Optional.of(entry)); }
Source:
<code>public long size() throws MessagingException { <START> Connection conn = null; <END> PreparedStatement count = null; ResultSet resultSet = null; try { conn = datasource.getConnection(); count = conn.prepareStatement(sqlQueries.getSqlString("countMessagesSQL", true)); resultSet = count.executeQuery(); return resultSet.next() ? resultSet.getLong(1) : 0; } catch (Exception e) { throw new MessagingException("Exception while removing mail: " + e.getMessage(), e); } finally { theJDBCUtil.closeJDBCResultSet(resultSet); theJDBCUtil.closeJDBCStatement(count); theJDBCUtil.closeJDBCConnection(conn); } }</code><technical_language>AFAIK jdbc objects handled a try-with-resource</technical_language>

Target:
public long size() throws MessagingException { try (Connection conn = datasource.getConnection(); PreparedStatement count = conn.prepareStatement(sqlQueries.getSqlString("countMessagesSQL", true)); ResultSet resultSet = count.executeQuery()) { return resultSet.next() ? resultSet.getLong(1) : 0; } catch (Exception e) { throw new MessagingException("Exception while fetching size: " + e.getMessage(), e); } }
Source:
<code>protected void setCategory(TextView textView, Trip data) { <START> textView.setText("Receipts: " + data.getSize()); <END> }</code><technical_language>This a R.string resource</technical_language>

Target:
protected void setCategory(TextView textView, Trip data) { textView.setText(getContext().getString(R.string.number_of_receipts, data.getSize())); }
Source:
<code>public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory) { final BaseObjectColumnValueSelector selector = metricFactory.makeColumnValueSelector(getName()); return new StringLastBufferAggregator(null, null, maxStringBytes) { @Override public void aggregate(ByteBuffer buf, int position) { SerializablePairLongString pair = (SerializablePairLongString) selector.getObject(); <START> if (pair != null && pair.rhs != null) { <END> ByteBuffer mutationBuffer = buf.duplicate(); mutationBuffer.position(position); long lastTime = mutationBuffer.getLong(position); if (pair.lhs >= lastTime) { mutationBuffer.putLong(position, pair.lhs); byte[] valueBytes = StringUtils.toUtf8(pair.rhs); mutationBuffer.putInt(position + Long.BYTES, valueBytes.length); mutationBuffer.position(position + Long.BYTES + Integer.BYTES); mutationBuffer.put(valueBytes); } } } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("selector", selector); } }; }</code><technical_language>here. lastTime check if pair.rhs is null</technical_language>

Target:
public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory) { final BaseObjectColumnValueSelector selector = metricFactory.makeColumnValueSelector(getName()); return new StringLastBufferAggregator(null, null, maxStringBytes) { @Override public void aggregate(ByteBuffer buf, int position) { SerializablePairLongString pair = (SerializablePairLongString) selector.getObject(); if (pair != null && pair.lhs != null) { ByteBuffer mutationBuffer = buf.duplicate(); mutationBuffer.position(position); long lastTime = mutationBuffer.getLong(position); if (pair.lhs >= lastTime) { mutationBuffer.putLong(position, pair.lhs); if (pair.rhs != null) { byte[] valueBytes = StringUtils.toUtf8(pair.rhs); mutationBuffer.putInt(position + Long.BYTES, valueBytes.length); mutationBuffer.position(position + Long.BYTES + Integer.BYTES); mutationBuffer.put(valueBytes); } else { mutationBuffer.putInt(position + Long.BYTES, 0); } } } } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("selector", selector); } }; }
Source:
<code>public Dialog onCreateDialog(final int id) { Dialog dialog = null; if (id == REALLY_REMOVE_DIALOG) { dialog = new AlertDialog.Builder(getActivity()) .setTitle(R.string.really_remove_account_title) .setMessage(R.string.really_remove_account_message) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.remove_account_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { AccountManager.get(AccountSyncSettings.this.getActivity()) .removeAccount(mAccount, new AccountManagerCallback<Boolean>() { public void run(AccountManagerFuture<Boolean> future) { if (!AccountSyncSettings.this.isResumed()) { return; } boolean failed = true; try { if (future.getResult() == true) { failed = false; } } catch (OperationCanceledException e) { } catch (IOException e) { } catch (AuthenticatorException e) { } <START> if (failed && !getActivity().isFinishing()) { <END> showDialog(FAILED_REMOVAL_DIALOG); } else { finish(); } } }, null); } }) .create(); } else if (id == FAILED_REMOVAL_DIALOG) { dialog = new AlertDialog.Builder(getActivity()) .setTitle(R.string.really_remove_account_title) .setPositiveButton(android.R.string.ok, null) .setMessage(R.string.remove_account_failed) .create(); } else if (id == CANT_DO_ONETIME_SYNC_DIALOG) { dialog = new AlertDialog.Builder(getActivity()) .setTitle(R.string.cant_sync_dialog_title) .setMessage(R.string.cant_sync_dialog_message) .setPositiveButton(android.R.string.ok, null) .create(); } return dialog; }</code><technical_language>check getActivity() return null</technical_language>

Target:
public Dialog onCreateDialog(final int id) { Dialog dialog = null; if (id == REALLY_REMOVE_DIALOG) { dialog = new AlertDialog.Builder(getActivity()) .setTitle(R.string.really_remove_account_title) .setMessage(R.string.really_remove_account_message) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.remove_account_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { AccountManager.get(AccountSyncSettings.this.getActivity()) .removeAccount(mAccount, new AccountManagerCallback<Boolean>() { public void run(AccountManagerFuture<Boolean> future) { if (!AccountSyncSettings.this.isResumed()) { return; } boolean failed = true; try { if (future.getResult() == true) { failed = false; } } catch (OperationCanceledException e) { } catch (IOException e) { } catch (AuthenticatorException e) { } if (failed && getActivity() != null && !getActivity().isFinishing()) { showDialog(FAILED_REMOVAL_DIALOG); } else { finish(); } } }, null); } }) .create(); } else if (id == FAILED_REMOVAL_DIALOG) { dialog = new AlertDialog.Builder(getActivity()) .setTitle(R.string.really_remove_account_title) .setPositiveButton(android.R.string.ok, null) .setMessage(R.string.remove_account_failed) .create(); } else if (id == CANT_DO_ONETIME_SYNC_DIALOG) { dialog = new AlertDialog.Builder(getActivity()) .setTitle(R.string.cant_sync_dialog_title) .setMessage(R.string.cant_sync_dialog_message) .setPositiveButton(android.R.string.ok, null) .create(); } return dialog; }
Source:
<code>public void execute(MethodTree methodTree) { <START> ExplodedGraphWalker walker = egwFactory.createWalker(behaviorCache, semanticModel); <END> try { Symbol.MethodSymbol methodSymbol = methodTree.symbol(); if (methodCanNotBeOverriden(methodSymbol)) { MethodBehavior methodBehavior = behaviorCache.methodBehaviorForSymbol(methodSymbol); if (!methodBehavior.isVisited()) { methodBehavior = walker.visitMethod(methodTree, methodBehavior); methodBehavior.completed(); } } else { walker.visitMethod(methodTree); } } catch (ExplodedGraphWalker.MaximumStepsReachedException | ExplodedGraphWalker.ExplodedGraphTooBigException | RelationalSymbolicValue.TransitiveRelationExceededException exception) { LOG.debug("Could not complete symbolic execution: ", exception); if (walker.methodBehavior != null) { walker.methodBehavior.visited(); } } }</code><technical_language>This a bit if creating a new access semantic model relying existing</technical_language>

Target:
public void execute(MethodTree methodTree) { ExplodedGraphWalker walker = egwFactory.createWalker(behaviorCache, (SemanticModel) context.getSemanticModel()); try { Symbol.MethodSymbol methodSymbol = methodTree.symbol(); if (methodCanNotBeOverriden(methodSymbol)) { MethodBehavior methodBehavior = behaviorCache.methodBehaviorForSymbol(methodSymbol); if (!methodBehavior.isVisited()) { methodBehavior = walker.visitMethod(methodTree, methodBehavior); methodBehavior.completed(); } } else { walker.visitMethod(methodTree); } } catch (ExplodedGraphWalker.MaximumStepsReachedException | ExplodedGraphWalker.ExplodedGraphTooBigException | RelationalSymbolicValue.TransitiveRelationExceededException exception) { LOG.debug("Could not complete symbolic execution: ", exception); if (walker.methodBehavior != null) { walker.methodBehavior.visited(); } } }
Source:
<code>public static PageResponse create(int size, int totalElements, int totalPages, int number) { <START> return new AutoValue_PageResponse(size, totalElements, totalPages, number); <END> }</code><technical_language>Validate inputs positive: <LINK_0></technical_language>

Target:
public static PageResponse create(int size, int totalElements, int totalPages, int number) { Preconditions.checkState(size >= 0, "Negative number of results on the page"); Preconditions.checkState(totalElements >= 0, "Negative number of results in the system"); Preconditions.checkState(totalPages >= 0, "Negative nubmer of pages"); Preconditions.checkState(number >= 0, "Negative number of items"); return new AutoValue_PageResponse(size, totalElements, totalPages, number); }
Source:
<code>public String generateHash() { final Hasher hasher = HASH_FUNCTION.newHasher(); if (key != null) { hasher.putString(key, Charsets.UTF_8); } for (final Map.Entry<String, String> kv : tags.entrySet()) { <START> final String k = kv.getKey(); <END> final String v = kv.getValue(); if (k != null) { hasher.putString(k, Charsets.UTF_8); } if (v != null) { hasher.putString(v, Charsets.UTF_8); } } return hasher.hash().toString(); }</code><technical_language>Is order for entrySet guaranteed time called? I for HashMaps, other Map implementations</technical_language>

Target:
public String generateHash() { final Hasher hasher = HASH_FUNCTION.newHasher(); if (key != null) { hasher.putString(key, Charsets.UTF_8); } TreeMap<String, String> sortedTags = new TreeMap<>(tags); for (final Map.Entry<String, String> kv : sortedTags.entrySet()) { final String k = kv.getKey(); final String v = kv.getValue(); if (k != null) { hasher.putString(k, Charsets.UTF_8); } if (v != null) { hasher.putString(v, Charsets.UTF_8); } } return hasher.hash().toString(); }