auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void writeToParcel(Parcel out, int flags) { out.writeString(user); out.writeString(interfaze); out.writeString(session); out.writeInt(mtu); out.writeTypedList(addresses); out.writeTypedList(routes); out.writeStringList(dnsServers); out.writeStringList(searchDomains); out.writeStringList(allowedApplications); out.writeStringList(disallowedApplications); out.writeParcelable(configureIntent, flags); out.writeLong(startTime); out.writeInt(legacy ? 1 : 0); out.writeInt(blocking ? 1 : 0); out.writeInt(allowBypass ? 1 : 0); out.writeInt(allowIPv4 ? 1 : 0); out.writeInt(allowIPv6 ? 1 : 0); out.writeTypedArray(underlyingNetworks, flags); <START> out.writeString(proxy == null ? "" : proxy.getHost()); out.writeInt(proxy == null ? 0 :proxy.getPort()); <END> }</code><technical_language>below; parcelable methods</technical_language>

Target:
public void writeToParcel(Parcel out, int flags) { out.writeString(user); out.writeString(interfaze); out.writeString(session); out.writeInt(mtu); out.writeTypedList(addresses); out.writeTypedList(routes); out.writeStringList(dnsServers); out.writeStringList(searchDomains); out.writeStringList(allowedApplications); out.writeStringList(disallowedApplications); out.writeParcelable(configureIntent, flags); out.writeLong(startTime); out.writeInt(legacy ? 1 : 0); out.writeInt(blocking ? 1 : 0); out.writeInt(allowBypass ? 1 : 0); out.writeInt(allowIPv4 ? 1 : 0); out.writeInt(allowIPv6 ? 1 : 0); out.writeTypedArray(underlyingNetworks, flags); out.writeParcelable(proxy, flags); }
Source:
<code>public void execute(List<VertexRef> targets, final OperationContext operationContext) { <START> if (targets == null || targets.isEmpty()) { <END> return; } final GraphContainer graphContainer = operationContext.getGraphContainer(); final Set<VertexHopCriteria> criteriaForGraphContainer = Criteria.getCriteriaForGraphContainer(graphContainer, VertexHopCriteria.class); for (VertexHopCriteria eachCriteria : criteriaForGraphContainer) { boolean shouldRemove = true; for (VertexRef vertex : eachCriteria.getVertices()) { if (targets.contains(vertex)) { shouldRemove = false; break; } } if (shouldRemove) { graphContainer.removeCriteria(eachCriteria); } } graphContainer.redoLayout(); }</code><technical_language>This is checked enabled() need checked twice</technical_language>

Target:
public void execute(List<VertexRef> targets, final OperationContext operationContext) { final GraphContainer graphContainer = operationContext.getGraphContainer(); final Set<VertexHopCriteria> criteriaForGraphContainer = Criteria.getCriteriaForGraphContainer(graphContainer, VertexHopCriteria.class); boolean didRemoveCriteria = false; for (VertexHopCriteria eachCriteria : criteriaForGraphContainer) { boolean shouldRemove = true; for (VertexRef vertex : eachCriteria.getVertices()) { if (targets.contains(vertex)) { shouldRemove = false; break; } } if (shouldRemove) { graphContainer.removeCriteria(eachCriteria); didRemoveCriteria = true; } } if (didRemoveCriteria) { graphContainer.redoLayout(); } }
Source:
<code><START> private void createAlertNotification(){ <END> Map<String, Object> ambariAlertNotifications = getConfig(AmbariCluster.AMBARI_ALERT_NOTIFICATIONS); createAlertNotification(mapAlertNotificationsConfigWithDefaults(ambariAlertsConfigFromProperties, ambariAlertNotifications)); }</code><technical_language>Put behavior method this protected</technical_language>

Target:
protected void createAlertNotification(){ Map<String, Object> ambariAlertNotifications = MutableMap.of(); for (Map.Entry config: getConfig(AmbariCluster.AMBARI_ALERT_NOTIFICATIONS).entrySet()) { Object value = (config.getValue() instanceof Map && !((String) config.getKey()).contains("properties")) ? ((Map) config.getValue()).keySet().toArray()[0] : config.getValue(); ambariAlertNotifications.put((String) config.getKey(), value); } Map<String, Object> mergedPropertiesConfig = MutableMap.of(); mergedPropertiesConfig.putAll((Map<String, Object>) getConfig(AmbariCluster.AMBARI_ALERT_NOTIFICATIONS).get("default_properties")); mergedPropertiesConfig.putAll((Map<String, Object>) ambariAlertNotifications.get("properties")); ambariAlertNotifications.put("properties", mergedPropertiesConfig); ambariAlertNotifications.remove("default_properties"); createAlertNotification(ambariAlertNotifications); }
Source:
<code>private PhysicalOperation createMergeSource(RemoteSourceNode node, LocalExecutionPlanContext context) { context.setDriverInstanceCount(1); checkArgument(node.getOrderingScheme().isPresent(), "orderingScheme is absent"); OrderingScheme orderingScheme = node.getOrderingScheme().get(); List<Type> types = getSourceOperatorTypes(node, context.getTypes()); <START> Map<Symbol, Integer> sourceLayout = makeLayoutFromOutputSymbols(node.getOutputSymbols()); <END> List<Symbol> orderBySymbols = orderingScheme.getOrderBy(); List<Integer> sortChannels = getChannelsForSymbols(orderBySymbols, sourceLayout); List<SortOrder> sortOrder = orderingScheme.getOrderingList(); ImmutableList<Integer> outputChannels = IntStream.range(0, types.size()) .boxed() .collect(toImmutableList()); OperatorFactory operatorFactory = new MergeOperatorFactory( context.getNextOperatorId(), node.getId(), exchangeClientSupplier, new PagesSerdeFactory(blockEncodingSerde, isExchangeCompressionEnabled(session)), new SimplePageWithPositionComparator.Factory(), types, outputChannels, sortChannels, sortOrder); return new PhysicalOperation(operatorFactory, makeLayout(node), context, UNGROUPED_EXECUTION); }</code><technical_language>makeLayout(node) remove makeLayoutFromOutputSymbols method. capture results in layout variable re-use in return new PhysicalOperation(operatorFactory, layout, context, UNGROUPED_EXECUTION);. I this code simplified removing orderBySymbols variable moving types closer is used. OrderingScheme orderingScheme = node.getOrderingScheme().get(); ImmutableMap<Symbol, Integer> layout = makeLayout(node); List<Integer> sortChannels = getChannelsForSymbols(orderingScheme.getOrderBy(), layout); List<SortOrder> sortOrder = orderingScheme.getOrderingList(); List<Type> types = getSourceOperatorTypes(node, context.getTypes()); ImmutableList<Integer> outputChannels = IntStream.range(0, types.size()) .boxed() .collect(toImmutableList());</technical_language>

Target:
private PhysicalOperation createMergeSource(RemoteSourceNode node, LocalExecutionPlanContext context) { checkArgument(node.getOrderingScheme().isPresent(), "orderingScheme is absent"); context.setDriverInstanceCount(1); OrderingScheme orderingScheme = node.getOrderingScheme().get(); ImmutableMap<Symbol, Integer> layout = makeLayout(node); List<Integer> sortChannels = getChannelsForSymbols(orderingScheme.getOrderBy(), layout); List<SortOrder> sortOrder = orderingScheme.getOrderingList(); List<Type> types = getSourceOperatorTypes(node, context.getTypes()); ImmutableList<Integer> outputChannels = IntStream.range(0, types.size()) .boxed() .collect(toImmutableList()); OperatorFactory operatorFactory = new MergeOperatorFactory( context.getNextOperatorId(), node.getId(), exchangeClientSupplier, new PagesSerdeFactory(blockEncodingSerde, isExchangeCompressionEnabled(session)), orderingCompiler, types, outputChannels, sortChannels, sortOrder); return new PhysicalOperation(operatorFactory, makeLayout(node), context, UNGROUPED_EXECUTION); }
Source:
<code>private boolean isValid(String validity) { int expiresOnIndex = validity.indexOf(X509CertificateParser.EXPIRES_ON_PREFIX); if(expiresOnIndex >= 0) { <START> SimpleDateFormat dateFormat = new SimpleDateFormat(X509CertificateParser.DATE_FORMAT, Locale.ENGLISH); <END> String expiresOn = validity.substring(expiresOnIndex + X509CertificateParser.EXPIRES_ON_PREFIX.length()).trim(); try { Date date = dateFormat.parse(expiresOn); return date.getTime() > System.currentTimeMillis(); } catch (ParseException e) { dateFormat = new SimpleDateFormat(X509CertificateParser.DATE_FORMAT); try { Date date = dateFormat.parse(expiresOn); return date.getTime() > System.currentTimeMillis(); } catch(ParseException e2) { OpenShiftUIActivator.getDefault().getLogger().logError("SSLCertificatesPreference.isValid(String): Could not parse '" + expiresOn + "' in format " + X509CertificateParser.DATE_FORMAT); } } } return true; }</code><technical_language>parsing a single class, X509CertificateParser, spread ones. Imho this method moved X509CertificateParser. SSLCertificatesPreference in ui while parser is in core hints this imho. In terms of separation of concerns a class handles preferences matters, parses certificate validity. this in fact this PR change in 2 locations, parsing certificate is spread 2 classes</technical_language>

Target:
private boolean isValid(String validity) { return X509CertificateParser.isValid(validity); }
Source:
<code>protected static Collection<Territory> findNearbyEnemyCapitalsAndFactories( final Territory startTerritory, final Set<Territory> enemyCapitalsAndFactories) { final var found = new HashSet<Territory>(); <START> final BreadthFirstSearch bfs = <END> new BreadthFirstSearch(startTerritory) { @Override public void visit(final Territory territory) { if (enemyCapitalsAndFactories.contains(territory)) { found.add(territory); } } @Override public boolean shouldContinueSearch(final int distanceSearched) { if (distanceSearched >= MIN_FACTORY_CHECK_DISTANCE && !found.isEmpty()) { return false; } return true; } }; bfs.search(); return found; }</code><technical_language>do of a var in order spell out variable name instead? eg: var breadthFirstSearch = new BreadthFirstSearch(startTerritory) {</technical_language>

Target:
protected static Collection<Territory> findNearbyEnemyCapitalsAndFactories( final Territory startTerritory, final Set<Territory> enemyCapitalsAndFactories) { final var found = new HashSet<Territory>(); new BreadthFirstSearch(startTerritory) .traverse( new BreadthFirstSearch.Visitor() { @Override public void visit(final Territory territory) { if (enemyCapitalsAndFactories.contains(territory)) { found.add(territory); } } @Override public boolean shouldContinueSearch(final int distanceSearched) { return distanceSearched < MIN_FACTORY_CHECK_DISTANCE || found.isEmpty(); } }); return found; }
Source:
<code>public void onUserLoginFailure(Exception ex, String accessToken, String backend) { tryToSetUIInteraction(true); logger.error(ex); if (ex instanceof HttpStatusException && ((HttpStatusException) ex).getStatusCode() == HttpStatus.FORBIDDEN) { RegisterActivity.this.showAlertDialog(getString(R.string.login_error), getString(R.string.auth_provider_disabled_user_error), getString(R.string.CUSTOMER_SUPPORT), (dialog, which) -> environment.getRouter() <START> .showFeedbackScreen(RegisterActivity.this, <END> getString(R.string.email_subject)), getString(android.R.string.cancel), null); } else { SocialFactory.SOCIAL_SOURCE_TYPE socialType = SocialFactory.SOCIAL_SOURCE_TYPE.fromString(backend); updateUIOnSocialLoginToEdxFailure(socialType, accessToken); } }</code><technical_language>change email subject</technical_language>

Target:
public void onUserLoginFailure(Exception ex, String accessToken, String backend) { tryToSetUIInteraction(true); logger.error(ex); if (ex instanceof HttpStatusException && ((HttpStatusException) ex).getStatusCode() == HttpStatus.FORBIDDEN) { RegisterActivity.this.showAlertDialog(getString(R.string.login_error), getString(R.string.auth_provider_disabled_user_error), getString(R.string.label_customer_support), (dialog, which) -> environment.getRouter() .showFeedbackScreen(RegisterActivity.this, getString(R.string.email_subject_account_disabled)), getString(android.R.string.cancel), null); } else { SocialFactory.SOCIAL_SOURCE_TYPE socialType = SocialFactory.SOCIAL_SOURCE_TYPE.fromString(backend); updateUIOnSocialLoginToEdxFailure(socialType, accessToken); } }
Source:
<code>protected void createFormContent(final IManagedForm managedForm) { super.createFormContent(managedForm); final ScrolledForm scrolledForm = managedForm.getForm(); FormToolkit toolkit = managedForm.getToolkit(); int sessionUriSegmentSize = session.getSessionResource().getURI().segmentsList().size(); scrolledForm.setText( <START> Messages.UI_SessionEditor_header_title_prefix + <END> session.getSessionResource().getURI().segmentsList().subList(1, sessionUriSegmentSize).stream().collect(Collectors.joining(DELIMITER))); toolkit.decorateFormHeading(scrolledForm.getForm()); Composite body = managedForm.getForm().getBody(); body.setLayout(GridLayoutFactory.swtDefaults().create()); informativeLabel = toolkit.createLabel(body, "Informative message."); informativeLabel.setForeground(body.getDisplay().getSystemColor(SWT.COLOR_RED)); Composite subBody = toolkit.createComposite(body); subBody.setLayout(GridLayoutFactory.swtDefaults().numColumns(2).equalWidth(false).create()); subBody.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); createModelsControl(toolkit, subBody); Composite rightComposite = toolkit.createComposite(subBody); rightComposite.setLayout(GridLayoutFactory.swtDefaults().margins(5, 0).create()); rightComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); createRepresentationsControl(toolkit, rightComposite); createViewpointSelectionControl(toolkit, rightComposite); }</code><technical_language>Avoid hard-coded prefix/suffix structure in translatable messages. Prefer MessageFormat.format(Messages.messageTemplate, values), is more flexible</technical_language>

Target:
protected void createFormContent(final IManagedForm managedForm) { super.createFormContent(managedForm); final ScrolledForm scrolledForm = managedForm.getForm(); FormToolkit toolkit = managedForm.getToolkit(); int sessionUriSegmentSize = session.getSessionResource().getURI().segmentsList().size(); scrolledForm.setText(MessageFormat.format(Messages.UI_SessionEditor_header_title_prefix, session.getSessionResource().getURI().segmentsList().subList(1, sessionUriSegmentSize).stream().collect(Collectors.joining(DELIMITER)))); toolkit.decorateFormHeading(scrolledForm.getForm()); Composite body = managedForm.getForm().getBody(); body.setLayout(GridLayoutFactory.swtDefaults().create()); informativeLabel = toolkit.createLabel(body, "Informative message."); informativeLabel.setForeground(body.getDisplay().getSystemColor(SWT.COLOR_RED)); Composite subBody = toolkit.createComposite(body); subBody.setLayout(GridLayoutFactory.swtDefaults().numColumns(2).equalWidth(false).create()); subBody.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); createModelsControl(toolkit, subBody); Composite rightComposite = toolkit.createComposite(subBody); rightComposite.setLayout(GridLayoutFactory.swtDefaults().margins(5, 0).create()); rightComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); createRepresentationsControl(toolkit, rightComposite); createViewpointSelectionControl(toolkit, rightComposite); }
Source:
<code>public ExprEval eval(ObjectBinding bindings) { ExprEval leftVal = left.eval(bindings); ExprEval rightVal = right.eval(bindings); <START> if (!NullHandling.useDefaultValuesForNull() && (leftVal.isNull() || rightVal.isNull())) { <END> return ExprEval.of(null); } if (leftVal.type() == ExprType.STRING && rightVal.type() == ExprType.STRING) { return evalString(leftVal.asString(), rightVal.asString()); } else if (leftVal.type() == ExprType.LONG && rightVal.type() == ExprType.LONG) { return ExprEval.of(evalLong(leftVal.asLong(), rightVal.asLong())); } else { return ExprEval.of(evalDouble(leftVal.asDouble(), rightVal.asDouble())); } }</code><technical_language>I find hard mentally follow phrase useDefaultValuesForNull(), negation in beginning. making methods more vivid names instead, - NullHandling.replace(), current useDefaultValuesForNull(), - NullHandling.sqlCompatible(), current !useDefaultValuesForNull()</technical_language>

Target:
public ExprEval eval(ObjectBinding bindings) { ExprEval leftVal = left.eval(bindings); ExprEval rightVal = right.eval(bindings); if (NullHandling.sqlCompatible() && (leftVal.isNull() || rightVal.isNull())) { return ExprEval.of(null); } if (leftVal.type() == ExprType.STRING && rightVal.type() == ExprType.STRING) { return evalString(leftVal.asString(), rightVal.asString()); } else if (leftVal.type() == ExprType.LONG && rightVal.type() == ExprType.LONG) { return ExprEval.of(evalLong(leftVal.asLong(), rightVal.asLong())); } else { return ExprEval.of(evalDouble(leftVal.asDouble(), rightVal.asDouble())); } }
Source:
<code>public void testTrace() { long[] time = new long[LOOP_COUNT]; for (int i = 0; i < LOOP_COUNT; i++) { IAnalysisModule module = new LttngKernelAnalysisModule(); module.setId("test"); <START> LttngKernelTrace trace = new LttngKernelTrace(); <END> try { trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class); module.setTrace(trace); } catch (TmfAnalysisException | TmfTraceException e) { fail(e.getMessage()); } long start = System.nanoTime(); TmfTestHelper.executeAnalysis(module); long end = System.nanoTime(); File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace)); for (File file : suppDir.listFiles()) { file.delete(); } testTrace.dispose(); time[i] = end - start; } double avg = 0, avgHot = 0; for (int i = 0; i < LOOP_COUNT; i++) { avg += time[i]; if (i > 2) { avgHot += time[i]; } } System.out.println("Cache cold : "+ String.format("%.3f", 0.000001 * time[0]) +"ms\t average time : " + String.format("%.3f", 0.000001 * avg / LOOP_COUNT) + " ms\t average (cache hot) time : " + String.format("%.3f", 0.000001 * (avgHot / LOOP_COUNT - 3))); }</code><technical_language>trace is close()'d (we enable "potential leak" warnings. module either</technical_language>

Target:
public void testTrace() { long[] time = new long[LOOP_COUNT]; for (int i = 0; i < LOOP_COUNT; i++) { IAnalysisModule module = new LttngKernelAnalysisModule(); module.setId("test"); try (LttngKernelTrace trace = new LttngKernelTrace()) { trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class); module.setTrace(trace); long start = System.nanoTime(); TmfTestHelper.executeAnalysis(module); long end = System.nanoTime(); File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace)); for (File file : suppDir.listFiles()) { file.delete(); } trace.dispose(); time[i] = end - start; } catch (TmfAnalysisException | TmfTraceException e) { fail(e.getMessage()); } } double avg = 0, avgHot = 0; for (int i = 0; i < LOOP_COUNT; i++) { avg += time[i]; if (i > 2) { avgHot += time[i]; } } System.out.println("Cache cold : " + String.format("%.3f", 0.000001 * time[0]) + "ms\t average time : " + String.format("%.3f", 0.000001 * avg / LOOP_COUNT) + " ms\t average (cache hot) time : " + String.format("%.3f", 0.000001 * (avgHot / LOOP_COUNT - 3))); }
Source:
<code>public boolean isSizeGreaterThan(int s) { if (sparseMap.size() + tempListIdx > s) { <START> mergeTempListToSparseMap(); <END> return sparseMap.size() > s; } return false; }</code><technical_language>tempList array added for insertion performance (at cost of slight misestimation duplicates in temp list) quickly buffer 1024 elements. This is negating merging sparse map more frequently. add sparse map instead of tempList getSize() a constant time operation. sparse register switch dense 3200 elements sparsemap a hot loop. I recommend removing tempList sparse register branching</technical_language>

Target:
public boolean isSizeGreaterThan(int s) { return sparseMap.size() > s; }
Source:
<code>public void notPossibleToLogInWhenUsernameFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn("", Configuration.getCredentials().password10); <START> Thread.sleep(1000); <END> Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); }</code><technical_language>do sleep ? is highly discouraged, wait for element instead</technical_language>

Target:
public void notPossibleToLogInWhenUsernameFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn("", Configuration.getCredentials().password10); Assertion.assertTrue(loginPage.isSubmitButtonDisabled(2)); }
Source:
<code>public List<UserVmVO> listByNetworkIdAndStates(long networkId, State... states) { NetworkVO network = networkDao.findById(networkId); if (UserVmSearch == null && network != null) { SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder(); nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); nicSearch.and("removed", nicSearch.entity().getRemoved(), SearchCriteria.Op.NULL); <START> if (! network.getGuestType().equals(Network.GuestType.L2)) { <END> nicSearch.and().op("ip4Address", nicSearch.entity().getIPv4Address(), SearchCriteria.Op.NNULL); nicSearch.or("ip6Address", nicSearch.entity().getIPv6Address(), SearchCriteria.Op.NNULL); nicSearch.cp(); } UserVmSearch = createSearchBuilder(); UserVmSearch.and("states", UserVmSearch.entity().getState(), SearchCriteria.Op.IN); UserVmSearch.join("nicSearch", nicSearch, UserVmSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); UserVmSearch.done(); } SearchCriteria<UserVmVO> sc = UserVmSearch.create(); if (states != null && states.length != 0) { sc.setParameters("states", (Object[])states); } sc.setJoinParameters("nicSearch", "networkId", networkId); return listBy(sc); }</code><technical_language>Space ! removed</technical_language>

Target:
public List<UserVmVO> listByNetworkIdAndStates(long networkId, State... states) { NetworkVO network = networkDao.findById(networkId); recreateUserVmSeach(network); SearchCriteria<UserVmVO> sc = UserVmSearch.create(); if (states != null && states.length != 0) { sc.setParameters("states", (Object[])states); } sc.setJoinParameters("nicSearch", "networkId", networkId); return listBy(sc); }
Source:
<code>protected void stopBackgroundDiscovery() { logger.debug("Stopping Astro device background discovery"); if (astroDiscoveryJob != null && !astroDiscoveryJob.isCancelled()) { <START> astroDiscoveryJob.cancel(true); <END> astroDiscoveryJob = null; logger.debug("Stopped Astro device background discovery"); } }</code><technical_language>returned boolean nullify astroDiscoveryJob print log</technical_language>

Target:
protected void stopBackgroundDiscovery() { logger.debug("Stopping Astro device background discovery"); if (astroDiscoveryJob != null && !astroDiscoveryJob.isCancelled()) { if (astroDiscoveryJob.cancel(true)) { astroDiscoveryJob = null; logger.debug("Stopped Astro device background discovery"); } } }
Source:
<code>public ApiFuture<RestoredTableResult> restoreTableAsync(RestoreTableRequest request) { return ApiFutureUtil.transformAndAdapt( delegate.restoreTableAsync( request.toProto(instanceName.getProjectId(), instanceName.getInstanceId())), new Function<Operation, RestoredTableResult>() { @Override public RestoredTableResult apply(Operation operation) { try { return new RestoredTableResult( Table.fromProto( operation.getResponse().unpack(com.google.bigtable.admin.v2.Table.class)), <START> ""); <END> } catch (InvalidProtocolBufferException e) { return new RestoredTableResult( Table.fromProto(com.google.bigtable.admin.v2.Table.getDefaultInstance()), ""); } } }); }</code><technical_language>I some change this code initially written java-bigtable repository created. In latest PR, restoreTableAsync returns ApiFuture<RestoredTableResult> instead of operation</technical_language>

Target:
public ApiFuture<RestoredTableResult> restoreTableAsync(RestoreTableRequest request) { return ApiFutureUtil.transformAndAdapt( delegate.restoreTableAsync( request.toProto(instanceName.getProjectId(), instanceName.getInstanceId())), new Function<Operation, RestoredTableResult>() { @Override public RestoredTableResult apply(final Operation operation) { try { Future<Operation> operationFuture = batchThreadPool.submit( new Callable<Operation>() { @Override public Operation call() throws Exception { return delegate.waitForOperation(operation); } }); return new RestoredTableResult( Table.fromProto( operationFuture .get() .getResponse() .unpack(com.google.bigtable.admin.v2.Table.class)), operation .getMetadata() .unpack(com.google.bigtable.admin.v2.RestoreTableMetadata.class) .getOptimizeTableOperationName()); } catch (IOException | InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } } }); }
Source:
<code>public List<TrackingEventResponse> getTrackingEvents() { <START> return trackingEvents; <END> }</code><technical_language>this List is a Java object, returning allows end user modify effect this object directly. handle this is a copy of object defensiveCopy return (like getThumbnails does)</technical_language>

Target:
public List<TrackingEventResponse> getTrackingEvents() { return defensiveCopy(this.trackingEvents); }
Source:
<code>private Constraint loadCost(ConstraintFactory factory) { return factory.from(MrMachineCapacity.class) .join(MrProcessAssignment.class, equal(MrMachineCapacity::getMachine, MrProcessAssignment::getMachine) ) <START> .groupBy((machineCapacity, processAssignment) -> machineCapacity, sumLong( (machineCapacity, processAssignment) -> processAssignment.getUsage(machineCapacity.getResource())) <END> ) .filter(((machineCapacity, usage) -> machineCapacity.getSafetyCapacity() < usage)) .penalizeLong(MrConstraints.LOAD_COST, HardSoftLongScore.ofSoft(1L), (machineCapacity, usage) -> usage - machineCapacity.getSafetyCapacity()); }</code><technical_language>chance sumLong() a new line, do in other constraints</technical_language>

Target:
private Constraint loadCost(ConstraintFactory factory) { return factory.from(MrMachineCapacity.class) .join(MrProcessAssignment.class, equal(MrMachineCapacity::getMachine, MrProcessAssignment::getMachine) ) .groupBy((machineCapacity, processAssignment) -> machineCapacity, sumLong((machineCapacity, processAssignment) -> processAssignment.getUsage(machineCapacity.getResource())) ) .filter(((machineCapacity, usage) -> machineCapacity.getSafetyCapacity() < usage)) .penalizeLong(MrConstraints.LOAD_COST, HardSoftLongScore.ONE_SOFT, (machineCapacity, usage) -> usage - machineCapacity.getSafetyCapacity()); }
Source:
<code>protected Set<Value.Immutable<?>> api$getVanillaValues() { Set<Value.Immutable<?>> vanillaValues = super.api$getVanillaValues(); <START> if (this.target != null) { <END> this.targetEntity().map(Value::asImmutable).ifPresent(vanillaValues::add); } vanillaValues.add(this.direction().asImmutable()); return vanillaValues; }</code><technical_language>Delete if, covered ifPresent</technical_language>

Target:
protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> values = super.api$getVanillaValues(); values.add(this.shooter().asImmutable()); this.targetEntity().map(Value::asImmutable).ifPresent(values::add); values.add(this.direction().asImmutable()); return values; }
Source:
<code>public void setup() throws ParseException { useTemplate = false; filename = null; useWorkflow = false; workflowNotify = false; if (commandLine.hasOption('h')) { help = true; return; } if (!commandLine.hasOption('f')) { throw new ParseException("Required parameter -f missing!"); } filename = commandLine.getOptionValue('f'); if (commandLine.hasOption('t')) { useTemplate = true; } if (commandLine.hasOption('w')) { useWorkflow = true; if (commandLine.hasOption('n')) { workflowNotify = true; } } else if (commandLine.hasOption('n')) { throw new ParseException( "Invalid option 'n': (notify) can only be specified with the 'w' (workflow) option."); } validateOnly = commandLine.hasOption('v'); try { c = new Context(); <START> c.turnOffAuthorisationSystem(); <END> } catch (Exception e) { throw new ParseException("Unable to create a new DSpace Context: " + e.getMessage()); } try { if (commandLine.hasOption('e')) { EPerson eperson; String e = commandLine.getOptionValue('e'); if (e.indexOf('@') != -1) { eperson = EPersonServiceFactory.getInstance().getEPersonService().findByEmail(c, e); } else { eperson = EPersonServiceFactory.getInstance().getEPersonService().find(c, UUID.fromString(e)); } if (eperson == null) { throw new ParseException("Error, eperson cannot be found: " + e); } c.setCurrentUser(eperson); } } catch (Exception e) { throw new ParseException("Unable to find DSpace user: " + e.getMessage()); } change = false; }</code><technical_language>Again, turning authorization checks leaving internalRun called. This is a bad practice</technical_language>

Target:
public void setup() throws ParseException { useTemplate = false; filename = null; useWorkflow = false; workflowNotify = false; if (commandLine.hasOption('h')) { help = true; return; } if (!commandLine.hasOption('f')) { throw new ParseException("Required parameter -f missing!"); } filename = commandLine.getOptionValue('f'); if (!commandLine.hasOption('e')) { throw new ParseException("Required parameter -e missing!"); } if (commandLine.hasOption('t')) { useTemplate = true; } if (commandLine.hasOption('w')) { useWorkflow = true; if (commandLine.hasOption('n')) { workflowNotify = true; } } else if (commandLine.hasOption('n')) { throw new ParseException( "Invalid option 'n': (notify) can only be specified with the 'w' (workflow) option."); } validateOnly = commandLine.hasOption('v'); change = false; }
Source:
<code>public void shutdown() { if (poisoned.compareAndSet(false, true)) { while (true) { <START> if (tasks.offer(POISON_PILL)) { <END> break; } } try { executorThread.join(); } catch (InterruptedException e) { } } }</code><technical_language>nit: I this re-factored to: java while (!task.offer(POISION_POLL) { // try }</technical_language>

Target:
public void shutdown() { if (poisoned.compareAndSet(false, true)) { while (!tasks.offer(POISON_PILL)) { } try { executorThread.join(); } catch (InterruptedException e) { } } }
Source:
<code>private String getSelectStatement(List<String> tables, List<String> columns, List<String> wheres) { <START> String schema = this.getSchema(); <END> String sql = ""; if (tables.isEmpty() || columns.isEmpty()) { return sql; } sql = "select "; for (String string : columns) { sql = sql + string + ","; } sql = sql.substring(0, sql.length() - 1) + " \nfrom "; for (String string : tables) { sql = sql + string + ","; } if (!wheres.isEmpty()) { sql = sql.substring(0, sql.length() - 1) + " \nwhere "; for (String string : wheres) { sql = sql + string + " and "; } } return sql; }</code><technical_language>need this code</technical_language>

Target:
private String getSelectStatement(List<String> tables, List<String> columns, List<String> wheres) { String sql = ""; if (tables.isEmpty() || columns.isEmpty()) { return sql; } sql = "select "; for (String string : columns) { sql = sql + string + ","; } sql = sql.substring(0, sql.length() - 1) + " \nfrom "; for (String string : tables) { sql = sql + string + ","; } if (!wheres.isEmpty()) { sql = sql.substring(0, sql.length() - 1) + " \nwhere "; for (String string : wheres) { sql = sql + string + " and "; } } return sql; }
Source:
<code>public void testValidateExternalVnicProfileMappingEmptyInputIsValid() { final List<ExternalVnicProfileMapping> vnicProfileMappings = <START> Collections.emptyList(); <END> final Set<EngineMessage> actual = underTest.validateExternalVnicProfileMapping(vnicProfileMappings, CLUSTER_ID); assertThat(actual, empty()); }</code><technical_language>static import</technical_language>

Target:
public void testValidateExternalVnicProfileMappingEmptyInputIsValid() { doTest(emptyList(), isValid()); }
Source:
<code>public long getEstimatedSizeInBytes() { <START> int result = INSTANCE_SIZE; <END> result += sizeOf(levelOffsets); result += tree.sizeOf(); for (T item : items) { result += item.getEstimatedSizeInBytes(); } return result; }</code><technical_language>result -> size</technical_language>

Target:
public long getEstimatedSizeInBytes() { long result = INSTANCE_SIZE + sizeOf(levelOffsets) + tree.sizeOf(); for (T item : items) { result += item.getEstimatedSizeInBytes(); } return result; }
Source:
<code>public static RenderingContextBuilder fillContext(RenderingContextBuilder builder, ServletRequest request) { builder.param(REQUEST_KEY, request); if (request instanceof HttpServletRequest) { HttpServletRequest webRequest = (HttpServletRequest) request; String baseURL = VirtualHostHelper.getBaseURL(request); if (webRequest.getUserPrincipal() != null) { CoreSession session = SessionFactory.getSession(webRequest); <START> builder.base(baseURL).session(session); <END> } Locale locale = request.getLocale(); if (locale != null) { builder.locale(locale); } Enumeration<String> headerNames = webRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headerValues = webRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { builder.param(headerName, headerValues.nextElement()); } } } for (Map.Entry<String, String[]> parameter : request.getParameterMap().entrySet()) { builder.paramValues(parameter.getKey(), (Object[]) parameter.getValue()); } Enumeration<String> attributeNames = request.getAttributeNames(); while (attributeNames.hasMoreElements()) { String attributeName = attributeNames.nextElement(); Object attributeValue = request.getAttribute(attributeName); builder.param(attributeName, attributeValue); } return builder; }</code><technical_language>fill baseURL for non-authenticated user</technical_language>

Target:
public static RenderingContextBuilder fillContext(RenderingContextBuilder builder, ServletRequest request) { builder.param(REQUEST_KEY, request); if (request instanceof HttpServletRequest) { HttpServletRequest webRequest = (HttpServletRequest) request; String baseURL = VirtualHostHelper.getBaseURL(request); builder.base(baseURL); builder.sessionWrapperSupplier(() -> { CoreSession session = SessionFactory.getSession(webRequest); return session == null ? null : new RenderingContext.SessionWrapper(session, false); }); Locale locale = request.getLocale(); if (locale != null) { builder.locale(locale); } Enumeration<String> headerNames = webRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headerValues = webRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { builder.param(headerName, headerValues.nextElement()); } } } for (Map.Entry<String, String[]> parameter : request.getParameterMap().entrySet()) { builder.paramValues(parameter.getKey(), (Object[]) parameter.getValue()); } Enumeration<String> attributeNames = request.getAttributeNames(); while (attributeNames.hasMoreElements()) { String attributeName = attributeNames.nextElement(); Object attributeValue = request.getAttribute(attributeName); builder.param(attributeName, attributeValue); } return builder; }
Source:
<code>private void fetchGalleryCollection() { updateProgressBar(true, true, 0); new GalleryCollectionFetchTask(app.getAPIForSite(pageTitle.getSite()), pageTitle.getSite(), pageTitle) { @Override public void onGalleryResult(GalleryCollection result) { updateProgressBar(false, true, 0); if (cacheOnLoad && page != null) { page.setGalleryCollection(result); app.getPageCache().put(pageTitle, page, new PageCache.CachePutListener() { @Override public void onPutComplete() { } @Override public void onPutError(Throwable e) { Log.e(TAG, "Failed to add page to cache.", e); } }); } applyGalleryCollection(result); } @Override public void onCatch(Throwable caught) { Log.e(TAG, "Failed to fetch gallery collection.", caught); updateProgressBar(false, true, 0); FeedbackUtil.showError(GalleryActivity.this, caught); <START> FeedbackUtil.showError(GalleryActivity.this, caught); <END> } }.execute(); }</code><technical_language>I assume this is duplicated unintentionally</technical_language>

Target:
private void fetchGalleryCollection() { updateProgressBar(true, true, 0); new GalleryCollectionFetchTask(app.getAPIForSite(pageTitle.getSite()), pageTitle.getSite(), pageTitle) { @Override public void onGalleryResult(GalleryCollection result) { updateProgressBar(false, true, 0); if (cacheOnLoad && page != null) { page.setGalleryCollection(result); app.getPageCache().put(pageTitle, page, new PageCache.CachePutListener() { @Override public void onPutComplete() { } @Override public void onPutError(Throwable e) { Log.e(TAG, "Failed to add page to cache.", e); } }); } applyGalleryCollection(result); } @Override public void onCatch(Throwable caught) { Log.e(TAG, "Failed to fetch gallery collection.", caught); updateProgressBar(false, true, 0); FeedbackUtil.showError(GalleryActivity.this, caught); } }.execute(); }
Source:
<code>public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { <START> try (IAnalysisModule module = createModule();) { <END> if (module != null) { return module.getAnalysisRequirements(); } return Collections.EMPTY_SET; } }</code><technical_language>if worth changing this, remove AutoCloseable IAnalysisModule, this _error_! *gasp*</technical_language>

Target:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { IAnalysisModule module = createModule(); if (module != null) { return module.getAnalysisRequirements(); } return Collections.EMPTY_SET; }
Source:
<code>private static String translateRef(String oldPrefix, String newPrefix, String ref) { <START> return newPrefix + ref.substring(oldPrefix.length()); <END> }</code><technical_language>I feel more comfortable this if throw IllegalArgumentException if !ref.startsWith(oldPrefix)</technical_language>

Target:
private static String translateRef(String oldPrefix, String newPrefix, String ref) { if (!ref.startsWith(oldPrefix)) throw new IllegalArgumentException(ref + " does not start with " + oldPrefix); return newPrefix + ref.substring(oldPrefix.length()); }
Source:
<code>public void add(HttpHeader header, String value) { <START> Objects.requireNonNull(header, "header"); <END> if (value == null) throw new IllegalArgumentException("null value"); HttpField field = new HttpField(header, value); add(field); }</code><technical_language>"header null"</technical_language>

Target:
public void add(HttpHeader header, String value) { Objects.requireNonNull(header, "header must not be null"); if (value == null) throw new IllegalArgumentException("null value"); HttpField field = new HttpField(header, value); add(field); }
Source:
<code><START> SearchRequest getNextPageParameters() { <END> return this.nextPageParameters; }</code><technical_language>reason this package private? This necessary continue a paged response set</technical_language>

Target:
public SearchRequest getNextPageParameters() { return this.nextPageParameters; }
Source:
<code>private static void fillDistributionMap(Map<String, Long> distributionMap, URIStatus status) { for (FileBlockInfo fileBlockInfo : status.getFileBlockInfos()) { long length = fileBlockInfo.getBlockInfo().getLength(); for (BlockLocation blockLocation : fileBlockInfo.getBlockInfo().getLocations()) { <START> distributionMap.put(blockLocation.getWorkerAddress().getHost(), <END> distributionMap.getOrDefault( blockLocation.getWorkerAddress().getHost(), 0L) + length); } } }</code><technical_language>distributionMap.compute instead of distributtionMap.put</technical_language>

Target:
private static void fillDistributionMap(Map<String, Long> distributionMap, URIStatus status) { for (FileBlockInfo fileBlockInfo : status.getFileBlockInfos()) { long length = fileBlockInfo.getBlockInfo().getLength(); for (BlockLocation blockLocation : fileBlockInfo.getBlockInfo().getLocations()) { distributionMap.compute(blockLocation.getWorkerAddress().getHost(), (hostName, totalLength) -> totalLength == null ? length : totalLength + length ); } } }
Source:
<code>@Test void testRowCountUnionDistinct() { <START> final String sql = "select x from (values 'a', 'b') as t(x)\n" <END> + "union\n" + "select x from (values 'a', 'b') as t(x)"; checkRowCount(sql, 2D, 2D, 4D); }</code><technical_language>select x values ('a', 'a') UNION DISTINCT select x values ('a', 'a') produce row right</technical_language>

Target:
@Test void testRowCountUnionDistinct() { String sql = "select x from (values 'a', 'b') as t(x)\n" + "union\n" + "select x from (values 'a', 'b') as t(x)"; checkRowCount(sql, 2D, 1D, 4D); sql = "select x from (values 'a', 'a') as t(x)\n" + "union\n" + "select x from (values 'a', 'a') as t(x)"; checkRowCount(sql, 2D, 1D, 4D); }
Source:
<code><START> public void shouldMapList() { <END> Source source = new Source(); source.setStringList( Arrays.asList( "Bob", "Alice" ).stream() ); Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getStringList() ).containsExactly( "Bob", "Alice" ); }</code><technical_language>@filiphr, I a generated code. I see: protected List<String> stringStreamToStringList(Stream<String> stream) { if ( stream == null ) { return null; } List<String> list = new ArrayList<String>(); list.addAll( stream.map( Function.identity() ) .collect( Collectors.toCollection( ArrayList<String>::new ) ) ); return list; } is identity function here? is assigning result a new list? I generate: protected List<String> stringStreamToStringList(Stream<String> stream) { if ( stream == null ) { return null; } return stream.collect( Collectors.toCollection( ArrayList<String>::new ) ); }</technical_language>

Target:
public void shouldMapList() { Source source = new Source(); source.setStringStream( Arrays.asList( "Bob", "Alice" ).stream() ); Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getStringList() ).containsExactly( "Bob", "Alice" ); }
Source:
<code>protected void doTestRenewAuth(boolean applyFix) throws IOException { getBlobStoreContext(applyFix); injectShortLivedTokenForSoftlayerAmsterdam(); context.getBlobStore().createContainerInLocation(null, testContainerName); assertContainerFound(); log.info("created container, now sleeping for expiration"); Time.sleep(Duration.TEN_SECONDS); if (!applyFix) { try { assertContainerFound(); Assert.fail("should fail as long as "+RetryOnRenew.class+" is not working"); <START> } catch (AssertionError e) { <END> log.info("failed, as expected: "+e); } getAuthCache().invalidateAll(); log.info("invalidated, should now succeed"); } assertContainerFound(); context.getBlobStore().deleteContainer(testContainerName); }</code><technical_language>This sense me. do Assert.fail() line 152, is guaranteed throw AssertionError, catch log expected it. I thought intent of catch-block assertContainerFound throw exception (not a failing assertion) token expired. I run it, I log message failed, expected: java.lang.AssertionError: fail long class org.jclouds.openstack.handlers.RetryOnRenew is working, suggestion "failed, expected" correct</technical_language>

Target:
protected void doTestRenewAuth(boolean applyFix) throws IOException { getBlobStoreContext(applyFix); injectShortLivedTokenForKeystoneV1_1(); context.getBlobStore().createContainerInLocation(null, testContainerName); assertContainerFound(); log.info("created container, now sleeping for expiration"); Time.sleep(Duration.TEN_SECONDS); if (!applyFix) { try { assertContainerFound(); } catch (Exception e) { log.info("failed, as expected: "+e); } getAuthCache().invalidateAll(); log.info("invalidated, should now succeed"); } assertContainerFound(); context.getBlobStore().deleteContainer(testContainerName); }
Source:
<code>private Map<Guid, Guid> mapDisks(DiskAttachments diskAttachments) { Map<Guid, Guid> diskToImageIds = null; if (diskAttachments.isSetDiskAttachments()) { diskToImageIds = diskAttachments.getDiskAttachments().stream() .map(DiskAttachment::getDisk) .filter(Objects::nonNull) <START> .map(d -> <END> (DiskImage) DiskMapper.map(d, null)) .collect(Collectors.toMap(BaseDisk::getId, DiskImage::getImageId)); } return diskToImageIds; }</code><technical_language>I is for readability complete names in cases: .map(disk -> (DiskImage) DiskMapper.map(disk, null))</technical_language>

Target:
private Map<Guid, Guid> mapDisks(DiskAttachments diskAttachments) { Map<Guid, Guid> diskToImageIds = null; if (diskAttachments.isSetDiskAttachments()) { diskToImageIds = diskAttachments.getDiskAttachments().stream() .map(DiskAttachment::getDisk) .filter(Objects::nonNull) .map(disk -> (DiskImage) DiskMapper.map(disk, null)) .collect(Collectors.toMap(BaseDisk::getId, DiskImage::getImageId)); } return diskToImageIds; }
Source:
<code>public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (grantResults.length == 0) { return; } if (requestCode == PERMISSION_READ_PHONE_STATE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { PackageManagerUtils.enableComponent(this, IncomingCallHandler.class, prefs.getBoolean("enable-phone-history", false)); } else { SwitchPreference p = (SwitchPreference) findPreference("enable-phone-history"); p.setChecked(false); Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show(); } } else if (requestCode == Permission.PERMISSION_WRITE_SETTINGS_EXTERNAL_STORAGE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, R.string.permission_restart, Toast.LENGTH_SHORT).show(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.permission_restart) .setCancelable(false) <START> .setPositiveButton("OK", new DialogInterface.OnClickListener() { <END> public void onClick(DialogInterface dialog, int id) { android.os.Process.killProcess(android.os.Process.myPid()); } }); AlertDialog alert = builder.create(); alert.show(); } else { Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show(); } } else if (requestCode == Permission.PERMISSION_READ_SETTINGS_EXTERNAL_STORAGE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { ImportExportHandler.loadSharedPreferencesFromFile(this, prefs); } else { Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show(); } } }</code><technical_language>OK translatable too</technical_language>

Target:
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (grantResults.length == 0) { return; } if (requestCode == PERMISSION_READ_PHONE_STATE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { PackageManagerUtils.enableComponent(this, IncomingCallHandler.class, prefs.getBoolean("enable-phone-history", false)); } else { SwitchPreference p = (SwitchPreference) findPreference("enable-phone-history"); p.setChecked(false); Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show(); } } else if ((requestCode == Permission.PERMISSION_WRITE_TO_EXTERNAL_STORAGE) || (requestCode == Permission.PERMISSION_READ_FROM_EXTERNAL_STORAGE)) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Permission.restartWithDialog(this); } else { Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show(); } } }